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

jef*_*unt 4 rspec stubbing ruby-on-rails-3

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

=link_to new_post_path
Run Code Online (Sandbox Code Playgroud)

但规范失败了:

ActionController::RoutingError: No route matches {:action=>"new", :controller=>"post"}
Run Code Online (Sandbox Code Playgroud)

我正在尝试存根该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")
Run Code Online (Sandbox Code Playgroud)

Mat*_*ell 5

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


dee*_*our 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")
Run Code Online (Sandbox Code Playgroud)