简体   繁体   中英

In Rspec, how test a controller action that does not have a route?

In a few of my controllers I have an action that does not have a corresponding route because it is accessed only via a render ... and return in other controller actions.

For example, I have an action

def no_such_page
 # displays a generic error screen
end

In my RSpec controller test, how do I 'get' that method and look at the response body?

If I try:

  get :no_such_page
  response.status.should be(200)

it of course gives the error

No route matches {:controller=>"foo", :action=>"{:action=>:no_such_page}"}

Update

Looking back over your question, it doesn't make sense to me now since you say that you are only accessing this action via render ... and return , but render renders a view, not an action. Are you sure that you even need this action? I think a view spec is the place for this test.

Original answer

It doesn't make sense to test the response code of an action which will never be called via an HTTP request. Likewise get :no_such_page doesn't make sense as you can't "get" the action (there is no route to it), you can only call the method.

In that sense, the best way to test it would be to treat it just like any other method on a class, in this case the class being your controller, eg PostsController . So you could do something like this:

describe PostsController do

  ... other actions ...

  describe "no_such_page" do
    it "displays a generic error screen" do
      p = PostsController.new
      p.should_receive(:some_method).with(...)
      p.no_such_page
    end
  end

end

But in fact, judging from what you've written, it sounds to me like your action has nothing in it, and you're just testing the HTML output generated by the corresponding view. If that's the case, then you really shouldn't be testing this in controller specs at all, just test it using a view spec , which is more appropriate for testing the content of the response body.

before :all do
  Rails.application.routes.draw do
    get '/no_such_page', to: "foo#no_such_page"
  end
end

after :all do
 Rails.application.reload_routes!
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM