如何在Rails中存根路径生成方法?

时间:2012-12-12 17:46:29

标签: ruby-on-rails-3 rspec stubbing

我正在编写一个视图规范,它会呈现一个包含该行的视图(以haml为单位):

=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")

3 个答案:

答案 0 :(得分:4)

如果您在视图规范中,但发现自己需要存根路径助手,则以下语法适用于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")

答案 1 :(得分:3)

方法new_post_path来自Rails.application.routes.url_helpers模块。您需要在该模块上存根方法

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

答案 2 :(得分: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")