Search code examples
ruby-on-railsrubyrspecrspec-rails

How to call the other of two similar routes in an RSpec controller spec?


Rails 4.1.8
Rspec 3.4.4

Given 2 routes, I'm having trouble understanding how to call them.

Route a) /data_services/add_comment/:id
Route b) /data_services/:id/add_comment

In services_controller_spec.rb

describe 'create comment' do
  let!(:service) { FactoryGirl.create(:service) }

  describe 'with valid comment' do
    it 'creates a new comment' do
      expect {
        post :add_comment, id: service.id
      }.to change(service.service_comments, :count).by(1)

      expect(response).to redirect_to(service_path(service))
    end
  end
end

I believe that with this code my test is referencing route a). How would I reference route b)?


Solution

  • When you call an action in an rspec-rails controller spec, you're not calling a route, you're calling the controller and action directly. The describe block that you pass the controller name to tells rspec-rails the class name, and the action name that you pass to the post or get call tells rspec-rails the method name. It just instantiates the controller class and calls the method directly.

    But, when the action method is called, Rails does look up the route to that controller and action and use it for a couple of incidental reasons, such as constructing the URI in request.env['PATH_INFO']. The route that's used depends on what's in your routes file, of course.

    So, to exercise a given route in a controller spec, call the controller and action that the route routes to.

    Note that rspec-rails also has routing specs, which are for directly testing what a route routes to.