【问题标题】:Devise sign_in_and_redirect causes rspec test to fail设计 sign_in_and_redirect 导致 rspec 测试失败
【发布时间】:2012-04-20 05:20:49
【问题描述】:

我对 TDD 有点陌生,所以如果这很明显,请原谅我,但我有一个使用 Devise 和 Omniauth 的登录系统,它在开发中完美运行,但出于某种原因,当我运行我的 rspec 测试,它失败了。

我正在测试我的身份验证控制器的创建操作

class AuthenticationsController < ApplicationController
  def create
    omniauth = request.env['omniauth.auth']
    authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
    if authentication
      flash[:notice] = "Signed in successfully"
      sign_in_and_redirect(:user, authentication.user)
    else
      user = User.find_by_email(omniauth['info']['email']) || User.new(:email => omniauth['info']['email'], :fname => omniauth['info']['first_name'], :lname => omniauth['info']['last_name']) 
      user.authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
      if user.save :validate => false
        flash[:notice] = "Login successful"
        sign_in_and_redirect(:user, user)
      else
        flash[:notice] = "Login failed"
        redirect_to root_path
      end
    end
  end
end

通过这个 rspec 测试

describe "GET 'create'" do
    before(:each) do
      request.env['omniauth.auth'] = { "provider" => "facebook", "uid" => "1298732", "info" => { "first_name" => "My", "last_name" => "Name", "email" => "myemail@email.com" } }
    end

    it "should create a user" do
      lambda do
        get :create
      end.should change(User, :count).by(1)
    end
  end

当我运行测试时,我得到了

Failure/Error: get :create
     NoMethodError:
       undefined method `user' for nil:NilClass
     # ./app/controllers/authentications_controller.rb:13:in `create'

确实,如果我删除了 sign_in_and_redirect 语句,测试就会通过。不过有趣的是,使用 sign_in 代替 sign_in_and_redirect 也会失败。

有人知道为什么会发生这种情况吗?特别是当我自己在开发中创建一个帐户时,它工作正常......

提前感谢您的帮助!

【问题讨论】:

  • 很确定我解决了自己的问题。显然,为了在测试中使用 Devise 的 sign_in 方法,您必须调用: include Devise::TestHelpers 包含它之后,我的问题就消失了,一切似乎都正常运行。

标签: ruby-on-rails rspec devise omniauth


【解决方案1】:

How To: Controllers and Views tests with Rails 3 (and rspec)

如果您使用 devise 的任何实用程序方法,控制器规范将无法开箱即用。

从 rspec-rails-2.0.0 和 devise-1.1 开始,将 devise 放入规范的最佳方法是将以下内容添加到 spec_helper 中:

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    相关资源
    最近更新 更多