让 Omniauth 模拟 Rails 中请求规范的登录



我写了一个测试来断言某些请求只能由登录用户执行,这些用户将使用Devise & Omniauth的Google OAuth2系统登录。我找不到一种方法来模拟全身份验证返回登录用户,从全身份验证 Wiki 页面中获取有关集成测试支持的示例

这是规格

describe "allows logged in users" do
before(:each) do
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:google, {:uid => '12345'})
Rails.application.env_config["devise.mapping"] = Devise.mappings[:user]
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:google]
end
it "new certification form" do
get new_certification_path
expect(response).to be_success
end
it "to create certification" do
certification_attributes = FactoryGirl.attributes_for :certification 
expect {
post "/certifications", params: { certification: certification_attributes }
}.to change(Certification, :count)
expect(response).to redirect_to certification_path
end
end

不用说,我无法破译给定错误的原因或失败位置,我认为这是因为用户无法登录

Failures:
1) Certifications allows logged in users new certification form
Failure/Error: expect(response).to be_success
expected `#<ActionDispatch::TestResponse:0x007fb23b4c2990 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mu..., @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil>>.success?` to return true, got false
# ./spec/requests/certifications_spec.rb:49:in `block (3 levels) in <top (required)>'
2) Certifications allows logged in users to create certification
Failure/Error:
expect {
post "/certifications", params: { certification: certification_attributes }
}.to change(Certification, :count)
expected #count to have changed, but is still 0
# ./spec/requests/certifications_spec.rb:54:in `block (3 levels) in <top (required)>'

我使用了错误的配置

这就进入了spec/support/rails_helper

OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:google_oauth2] = OmniAuth::AuthHash.new({
:provider => "google_oauth2",
:uid => "123456789",
:info => {
:name => "Tony Stark",
:email => "tony@stark.com"
},
:credentials => {
:token => "token",
:refresh_token => "refresh token"
}
}
)

然后是 Before 方法

before(:each) do
Rails.application.env_config["devise.mapping"] = Devise.mappings[:user]
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:google_oauth2]
end

最新更新