rspec-rails tricks: Hacking Your Routes for a Spec

I don't know that this is so much a reminder of "What can be done with rspec-rails" as a note that, "If you do this will rspec-rails, you will also need to undo it."

Today's note: If you hack the application routes for a controller test, you have to reload routes.

The original problem

This all came down to a spec that was attempting to test a method in ApplicationController. In our Rails 3 setup (rspec-core and rspec-rails 3.7.0), the tests only needed a monkey patched ApplicationController to happen prior to the test:

before do
  class ApplicationController
    def dummy_action
      dummy_method_actually_under_test
    end
  end
end
 
it 'example do test' do
  get :dummy_action #etc...
  # validate dummy_method_actually_under_test did the thing
end

The fix

In Rails 4 with the same gem versions, we'd end up with the "No route matches..." which could be remedied by redefining the routes.

before do
  class ApplicationController
    def dummy_action
      dummy_method_actually_under_test
    end
  end
  Rails.application.routes.draw do
    get 'application/dummy_action/:id', to: 'application#dummy_action'
  end
end

Great! The test passes now! (Insert philosophical argument about whether the person writing the test should have tested a method in this way.)

Or not...

..until you run the rest of the suite, of course. Now *every* subsequent controller test has a "No route matches" issue. (Insert philosophical argument about whether you should be writing controller tests.)

This should serve as a periodic reminder to clean up after your tests, which in this case is:

after do
  Rails.application.reload_routes!
end