2012-04-20 92 views
2

我对TDD很陌生,所以如果这是显而易见的,您将不得不原谅我,但我有一个使用Devise和Omniauth的登录系统,可以在开发中完美工作,但由于某种原因,当我运行我的rspec测试时,它失败了。设计sign_in_and_redirect会导致rspec测试失败

我这个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 

describe "GET 'create'" do 
    before(:each) do 
     request.env['omniauth.auth'] = { "provider" => "facebook", "uid" => "1298732", "info" => { "first_name" => "My", "last_name" => "Name", "email" => "[email protected]" } } 
    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也失败了。

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

在此先感谢您的帮助!如果你使用任何的色器件的实用方法

+2

肯定我解决了我自己问题。 显然,为了使用测试中制定的sign_in方法,你必须调用: 包括制定:: TestHelpers 包括它之后,我的问题走了,一切似乎都正常。 – 2012-04-20 06:45:51

回答

0

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

控制器规格也不会开箱工作。

作为RSpec的护栏-2.0.0,并制定-1.1,把设计在您的规格的最佳方法是简单地添加以下到spec_helper:

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