I'm writing a view spec, and it renders a view that contains the line (in haml):

=link_to new_post_path

but the spec fails with:

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

I'm trying to stub the new_post_path method, as it's not actually important to the view spec, but haven't had any luck.

I've tried, within my spec, the following two variations without any luck:

           stub!(:new_post_path).and_return("this path isn't important")
controller.stub!(:new_post_path).and_return("this path isn't important")
有帮助吗?

解决方案 2

The method new_post_path comes from the Rails.application.routes.url_helpers module. You need to stub the method on that module

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

其他提示

If you're not in a view spec, but find yourself needing to stub a path helpers, the following syntax works as of Rails 4.2.5; you'll need to receive_message_chain instead as described here:

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

To wit:

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

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

that is rspec 3.2 syntax

I guess the old syntax would be

view.stub(:new_post_path).and_return("this path isn't important")
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top