How to request (GET/POST) routes in RSpec that have a wildcard

23,577

(Answering my own question)

This turned out to be a bit of a 'rookie' mistake.

The wildcard (event) part of the route still requires a parameter. I wasn't passing the 'event' parameter, therefore the route was incomplete.

The following code works:

describe "post_event" do

  it "should respond with 204" do
    params = {
      attachment_id: @attachment.uid,
      software_id: @license.id,
      event: 'some/event'
    }

    post :post_event, params

    response.code.should eq "204"
  end
end

/*event(.:format) means it's expecting a parameter.

Special note to self and others:

If you ever have routing errors in Rails, verify that you're passing all the parameters.

Share:
23,577
campeterson
Author by

campeterson

Updated on March 06, 2020

Comments

  • campeterson
    campeterson about 4 years

    I have this (admittedly hideous) route in Rails:

    scope '/software' do
      post '/:software_id/:attachment_id/event/*event' => 'software#post_event', as: 'post_event'
    end
    

    (I would change it but for a legacy API)

    And I am writing an RSpec test for it.

    rake routes gives me:

    post_event POST   /software/:software_id/:attachment_id/event/*event(.:format)     api/version1301/software#post_event
    

    My test looks like this:

      describe "post_event" do
    
        it "should respond with 204" do
          params = {
            attachment_id: @attachment.uid,
            software_id: @license.id
          }
    
          post :post_event, params
    
          response.code.should eq "204"
        end
      end
    

    But I get the following routing error:

    Failure/Error: post :post_event, params
    ActionController::RoutingError:
    No route matches {:format=>"json", :name_path=>:api, :attachment=>"7b40ab6a-d522-4a86-b0de-dfb8081e4465", :software_id=>"0000001", :attachment_id=>"7b40ab6a-d522-4a86-b0de-dfb8081e4465", :controller=>"api/version1301/software", :action=>"post_event"}
         # ./spec/controllers/api/version1301/software_controller_spec.rb:62:in `block (4 levels) in '
    

    How do you handle the route with the wildcard (event)?

  • Mahendar Patel
    Mahendar Patel almost 10 years
    Had a similar problem with an engine mounted inside a scope: scope "*lang" { mount XX::Engine, at: '/' }. I had to pass in 'lang: "en"' to the get in the test to make it work.... that took me 2 days to find.....
  • Epigene
    Epigene about 7 years
    Lately I've been writing routing specs for all non-RESTful routes I encounter. Has saved some headache.