rspec – 在OmniAuth的集成测试中获取nil的“undefined方法`env’:NilClass”

我有Omniauth测试模式:

spec_helper(我把它放在文件的底部,就在结束之前):

#Turn on "test mode" for OmniAuth 
OmniAuth.config.test_mode = true

这是我的考验:

规格/请求/ authorization_pages_spec.rb:

 describe "signin" do
    before { visit signin_path }
    .
    .
    .
    describe "with OmniAuth" do
      before do
        OmniAuth.config.add_mock :facebook, uid: "fb-12345", info: { name: "Bob Smith" }
        visit root_path
      end

      describe "Facebook provider" do
        before do
          request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
          click_link "Sign in with Facebook"
        end

        it { should have_selector('title', text: user.name) }

        it { should have_link('Users',    href: users_path) }
        it { should have_link('Profile',  href: user_path(user)) }
        it { should have_link('Settings', href: edit_user_path(user)) }
        it { should have_link('Sign out', href: signout_path) }

        it { should_not have_link('Sign in', href: signin_path) }
      end

当我运行我的测试时,我得到了这个:

失败:

  1) Authentication signin with OmniAuth Facebook provider 
     Failure/Error: request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
     NoMethodError:
       undefined method `env' for nil:NilClass
     # ./spec/requests/authentication_pages_spec.rb:57:in `block (5 levels) in <top (required)>'

(等等).

有什么东西丢失或我做错了吗?

最佳答案 我想你在这个例子中混合了两个不同的东西.您正在尝试编写集成规范,但请求方法AFAIK仅在控制器规范中可用(对于spec / controllers目录中的规范).因此,对于nil:NilClass`错误,您有未定义的methodenv’.

您可以在我的示例项目中找到健康的OmniAuth集成规范:https://github.com/lucassus/locomotive/blob/9cd7dfd365469fc70fc367f29705a56df9730f6f/spec/features/user_facebook_sign_in_spec.rb

我希望它会对你有所帮助.

点赞