设计sign_in_and_redirect导致rspec测试失败

时间:2012-04-20 05:20:49

标签: ruby-on-rails rspec devise omniauth

我对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也会失败。

有人知道为什么会这样吗?特别是因为当我自己在开发中创建一个帐户时,它工作得很好......

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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

  

如果您正在使用任何设计实用程序方法,控制器规格将不会开箱即用。

     

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

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