2013-12-16 40 views
10

我正在構建一個rails 4應用程序,我正面臨一個奇怪的問題:我創建的模擬登錄名的支持文件給了我一個未定義的方法錯誤。rspec如何在rails 4中包含支持文件?

以下是文件

#spec/support/spec_test_helper.rb 
module SpecTestHelper 
    def login(user) 
    request.session[:user_id] = user.id 
    end 

    def current_user 
    User.find(request.session[:user_id]) 
    end 
end 

#spec_helper.rb 

config.include SpecTestHelper, :type => :controller 

,並在我的控制器規範

describe BooksController, "user role" do 

    user = Fabricate(:user) do 
    role { Role.find_by_account_type("user") } 
    end 

    login(user) 
end 

BTW我測試慘慘;我知道正確的方式來測試康康舞測試能力,但是這已經做了:)

這是錯誤消息的一部分:

spec/controllers/books_controller_spec.rb:27:in `block in <top (required)>': undefined method `login' for #<Class:0x007f9f83193438> (NoMethodError) 
+0

請包括確切的錯誤信息。 – screenmutt

回答

2

將一個beforeit塊內的login(user)調用,而不是直接內describe

let(:user) do 
    Fabricate(:user) do 
    role { Role.find_by_account_type("user") } 
    end 
end 

before do 
    login(user) 
end 
+0

是的!非常感謝你的問題。 – Ricbermo

20

spec_helper.rb加入這一行,並在第3 Rails的工作

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

也許另一個(更漂亮)解決方案存在

+0

我的spec_helper.rb已經有了它。謝謝 – Ricbermo

+1

所以要注意@Ash的答案 - 你真的應該建立記錄和調用方法在裏面/之前/讓... – gotva

2

替代由@gotva提供了答案。這是稍微詳細,但將在兩個軌道3和4的工作:

Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f} 
7

我使用的軌道的4.2.4版本,我掙扎昨天添加的支持文件夾下的文件。 問題是,我沒有注意到rspec目錄下的兩個文件的不同目的。我有rails_helper.rb和spec_helper.rb。如果你想爲軌道相關類的支持,你應該使用rails_helper告訴軌加載「規格/支持」 DIR

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

,並宣佈要內使用共享模塊下的模塊配置塊。

RSpec.configure do |config| 
    ... 
    config.include <YourModuleName>::<YourClassName>, :type => :controller 
    ... 
end 

但是,如果你的類不需要導軌的一切,你可以在spec_helper加載它,它不會加載軌運行測試。 參考this answerthis reference瞭解更多信息。

相關問題