2012-11-15 48 views
2

我正在使用Rspec,FactoryGirl和Spork進行測試。有兩件事我是litte不清楚的,首先是我的factories.rb文件的位置。目前我有它位於FactoryGirl,Rspec2和devise rails 3

spec/support/factories.rb 

而且它看起來像這樣

FactoryGirl.define do 
factory :user do 
email     "[email protected]" 
password    "password" 
password_confirmation "password" 
confirmed_at   Time.now 

end 
end 

在我的spec_helper我有

config.include FactoryGirl::Syntax::Methods 

其次我想開始我的試驗之前,登錄用戶一個控制器,這個特定的控制器有一個before過濾器:authenticate_user!

我使用的設計我的身份驗證,因此增加了

config.include Devise::TestHelpers, :type => :controller 

讀色器件文檔,你可以添加一個controller_macros.rb並指定像這樣使用

def login_user 
before(:each) do 
    @request.env["devise.mapping"] = Devise.mappings[:user] 
    user = FactoryGirl.create(:user) 
    user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are  using the confirmable module 
    sign_in user 
    end 
    end 

方法,所以我加入這也給我的spec_helper

config.include ControllerMacros, :type => :controller 

所以,當我在我的控制之前添加login_user呃測試我得到未定義的方法login_user。我在這裏使用兩個工具來做同樣的事情嗎?我真的需要設計方法,還是可以用factoryGirl完成所有工作?如果是這樣,我可以在測試控制器之前設置登錄過程?

回答

2

工廠的位置應在spec/factories。看看這個示例應用程序https://github.com/RailsApps/rails3-devise-rspec-cucumber/tree/master/spec

對於登錄,通常你似乎做得對。一次在這裏檢查示例應用程序:https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-%28and-rspec%29

對於undefined method login_user錯誤一定要有

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} 

config.extend ControllerMacros, :type => :controller 
在spec_helper

。設計方法應該可用於主題:

subject.current_user.should_not be_nil