5

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")
jefflunt
  • 33,527
  • 7
  • 88
  • 126

3 Answers3

5

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

Matt Mitchell
  • 109
  • 1
  • 4
  • or you could just stub the view as in my answer above rather than stubbing Rails.application – ryan2johnson9 May 31 '17 at 04:16
  • That works if you are in a view spec (and admittedly that was the original question), but that wasn't the case I was grappling with. I'll update my answer to reflect that. – Matt Mitchell Jul 12 '17 at 19:21
3

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")
deefour
  • 34,974
  • 7
  • 97
  • 90
  • Thanks, it turns out that my error was actually elsewhere, but you did help me to find out how to stub it. – jefflunt Dec 12 '12 at 19:50
  • 1
    this only works for me if I use `Rails.application.routes.url_helpers.new_host_path` in my view as opposed to the normal `new_host_path` p.s. I'm using rspec 3.2 syntax `allow(Rails.application.routes.url_helpers).to receive(:new_host_path).and_return("/")` – ryan2johnson9 Jun 15 '15 at 01:44
  • 1
    @ryan2johnson9 If you figured it out, would you mind posting your solution? I'm having the same issue. – Chris Bloom Jun 16 '15 at 21:40
3
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")
ryan2johnson9
  • 724
  • 6
  • 21