私は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_and_redirect の代わりに sign_in を使用しても失敗します。
なぜこれが起こるのか知っている人はいますか?特に、開発中に自分でアカウントを作成するとうまくいくので...
助けてくれてありがとう!