我对 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 也失败了。
有谁知道为什么会发生这种情况?特别是当我自己在开发中创建一个帐户时,它工作得很好......
在此先感谢您的帮助!