0

我编写了一个测试来断言某些请求只能由登录用户执行,这些用户将使用 Devise & Omniauth 的 Google OAuth2 系统登录。我找不到模拟omniauth返回登录用户的方法,从Omniauth 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)>'
4

1 回答 1

2

我使用了错误的配置

这进入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
于 2017-08-01T07:15:46.690 回答