2012-12-12 43 views
1

我正在寫一個視圖規範,它使得包含行(HAML)一個觀點:如何在Rails中存根路徑生成方法?

=link_to new_post_path 

但與規範失敗:

ActionController::RoutingError: No route matches {:action=>"new", :controller=>"post"} 

我試圖存根new_post_path方法,因爲它對於視圖規範並不重要,但沒有任何運氣。

我試過,我的規格內,下面的兩個變化沒有任何的運氣:

  stub!(:new_post_path).and_return("this path isn't important") 
controller.stub!(:new_post_path).and_return("this path isn't important") 

回答

2

的方法new_post_path來自Rails.application.routes.url_helpers模塊。您需要存根方法模塊上

Rails.application.routes.url_helpers.stub(:new_post_path).and_return("this path isn't important") 
+0

謝謝,事實證明,我的錯誤實際上是在其他地方,你卻幫我找到了解如何存根。 – jefflunt

+1

這隻適用於我,如果我在我的視圖中使用'Rails.application.routes.url_helpers.new_host_path'而不是正常的'new_host_path' p.s.我使用rspec 3.2語法'allow(Rails.application.routes.url_helpers).to receive(:new_host_path).and_return(「/」)' – ryan2johnson9

+1

@ ryan2johnson9如果你知道了,你介意發佈你的解決方案嗎?我有同樣的問題。 –

3
allow(view).to receive(:new_post_path).and_return("this path isn't important") 

是RSpec的3.2語法

我猜老語法將

view.stub(:new_post_path).and_return("this path isn't important") 
+0

感謝您分享您的修復。 –

+0

我發現這與RSpec 3.5一起使用。 'view.stubs(:new_post_path).returns(「這個路徑並不重要」)' – scarver2

2

如果你是一個視圖規範,但發現自己需要存根路徑助手,以下語法適用於Rails 4.2.5;你需要receive_message_chain代替如下所述:

https://github.com/rspec/rspec-mocks/issues/1038

機智:

allow(Rails.application).to receive_message_chain(:routes, :url_helpers, :new_post_path).and_return("this path isn't important")

+0

或者你可以像上面的回答那樣存留視圖,而不是存儲Rails.application – ryan2johnson9

+0

如果你處於視圖規範(無可否認,這是原來的問題),但我並不是那麼努力的。我會更新我的答案以反映這一點。 –

相關問題