2013-04-30 55 views
1

我是Rails的新手。我使用FactoryGirl爲我的集成測試創建用戶,但我無法弄清楚如何在測試中登錄我的用戶。NoMethodError:未定義的方法`sign_in_as!',FactoryGirl,Rspec,Rails

我廠是這樣的:

FactoryGirl.define do 
    factory :user do 
     sequence(:email) { |n| "user#{n}@ticketee.com" } 
     password "password" 
     password_confirmation "password" 
    end 

    factory :confirmed_user do 
     after_create { |user| user.confirm! } 
    end 
end 

而且我的測試是這樣的:

feature 'Editing an exercise' do 

    before do 
     ex = FactoryGirl.create(:ex) 
     user = FactoryGirl.create(:user) 
     user.confirm! 
     sign_in_as!(user) 
    end 

    scenario 'can edit an exercise' do 
     visit '/' 
     click_link 'Exercises' 
     click_link 'running' 
     click_link 'edit' 
     fill_in 'Name', :with => 'kick boxing' 
     fill_in 'Description', :with => 'kicking a box' 
     click_button 'Save' 
     page.should have_content('Exercise updated!') 
     page.should have_content('kick boxing') 
    end 
end 

當我運行測試我得到的錯誤:

Failure/Error: sign_in_as!(user) 
NoMethodError: 
undefined method `sign_in_as!' 
for #<RSpec::Core::ExampleGroup::Nested_1:0xb515ecc> 

的應用效果很好,只是測試失敗。任何幫助,將不勝感激。謝謝!

回答

0

其中是sign_in_as!界定?在我看來,它是在ApplicationController中定義的,因此在您的測試中不可用。

你可能已經有一個集成測試登錄您的用戶,這樣的事情:

scenario "user logs in" do 
    visit '/' 
    fill_in "Username", with: "username" 
    ... 
end 

如果這是你應該能夠大部分代碼拉出到一個輔助方法和使用情況在你的面前塊

編輯: 我剛纔想通了,你很可能使用設計,在這種情況下,你應該修改你的spec_helper.rb這樣的:

RSpec.configure do |c| 
    ... 
    c.include Devise::TestHelpers 
    ... 
end 

並使用sign_in而不是sign_in_as!

+1

是的,我正在使用Devise。我添加了c.include Devise :: TestHelpers到我的spec_helper文件,現在錯誤是失敗/錯誤:sign_in(user) NoMethodError: 未定義的方法'env'for nil:NilClass – 2013-04-30 01:51:43

+0

我讀過了github上的devise文檔http: //github.com/plataformatec/devise再次。在測試助手部分中,聲明Devise沒有提供任何助手進行集成測試。似乎正在創建/重構「用戶登錄」測試,就像我建議的那樣。 – 2013-04-30 02:03:08

1

你是對的,我的測試找不到sign_in_as!和我最後寫一個驗證輔助器,看起來像這樣:

module AuthenticationHelpers 
    def sign_in_as!(user) 
     visit '/users/sign_in' 
     fill_in "Email", :with => user.email 
     fill_in "Password", :with => "password" 
     click_button "Sign in" 
     page.should have_content("Signed in successfully.") 
    end 
end 

RSpec.configure do |c| 
    c.include AuthenticationHelpers, :type => :request 
end 

和規格/支持/ authentication_helpers.rb堅持到底。這工作。 感謝您的幫助!

相關問題