2013-04-16 29 views
5

我有一個RSpec規格:如何在運行槽Spork時在ApplicationHelper Spec中包含路由?

require "spec_helper" 

describe ApplicationHelper do 
    describe "#link_to_cart" do 
    it 'should be a link to the cart' do 
     helper.link_to_cart.should match /.*href="\/cart".*/ 
    end 
    end 
end 

而且ApplicationHelper:

module ApplicationHelper 
    def link_to_cart 
    link_to "Cart", cart_path 
    end 
end 

訪問該網站時,此工作,但規格失敗,並拋出一個RuntimeError關於路由不是可供選擇:

RuntimeError: 
    In order to use #url_for, you must include routing helpers explicitly. For instance, `include Rails.application.routes.url_helpers 

所以,我在我的規範中包含Rails.application.routes.url,文件spec_helper甚至ApplicationHelper本身,t o無濟於事。

編輯:我正在通過spork運行測試, 也許與它有關 並導致此問題。

與Spork一起運行時,如何包含這些路線助手?

回答

7

您需要在ApplicationHelper的模塊級別添加include,因爲默認情況下,ApplicationHelper不包含url助手。這樣的代碼

module AppplicationHelper 
    include Rails.application.routes.url_helpers 

    # ... 
    def link_to_cart 
    link_to "Cart", cart_path 
    end 

end 

然後代碼將工作,您的測試將通過。

+0

我已經試過了,它不會讓測試通過:失敗消息保持不變。 – berkes

+1

@berkes,我已經在發佈答案之前在我的控制檯中驗證過。有用。在你的問題中,我只看到你提到包括它在測試中,但沒有ApplicationHelper模塊。這是不正確的。 –

+0

它也不是'ApplicationController',但'ApplicationHelper' –

4

如果使用sporkrspec,你應該url_helper方法添加到您的rspec的配置 -

裏面的 '/規格/ spec_helper' 文件:

RSpec.configure do |config| 
. 
. =begin 
. bunch of stuff here, you can put the code 
. pretty much anywhere inside the do..end block 
. =end 
config.include Rails.application.routes.url_helpers 
. 
. #more stuff 
end 

這個加載內置ApplicationHelper調用「Routes」並將'#url_helpers'方法調用到RSpec中。沒有必要將它添加到'/app/helpers/application_helper.rb'中的ApplicationHelper中,原因有兩個:

1)您只是將'routes'功能複製到一個不需要它的地方,本質上控制器,它已經從ActionController :: Base(我認爲可能::金屬,現在不重要)繼承它。這樣你就不會被幹 - 不要重複自己

2)此錯誤是特定於RSpec的配置,解決它在那裏它打破了(我自己的小格言)

接下來,我建議你固定測試一點。試試這個:

require "spec_helper" 

describe ApplicationHelper do 
    describe "#link_to_cart" do 
    it 'should be a link to the cart' do 
    visit cart_path 
    expect(page).to match(/.*href="\/cart".*/) 
    end 
    end 
end 

我希望這對某人有幫助!

0

我正在使用guardspring我發現,在我的情況下,這個問題是由春天造成的。運行後spring stop已修復。但是當我改變ApplicationController中的某些東西時,它有時會回來。

相關問題