Search code examples
ruby-on-rails-3rspec2glob

how can I rspec test a controller with route globbing


To get a list of questionnaires I use the

GET "/questionnaires/user/1/public/true/mine/true/shared/true"

in routes.rb I have

/questionnaires/*myparams(.:format)  {:controller=>"questionnaires", :action=>"list"}

The controller uses route globbing to create a query in the list method

class QuestionnairesController < ApplicationController
  before_filter :authenticate  

  def list  
    myparams = params[:myparams].split("/").to_h
  end

  # ...
end

I am trying to create the test cases for all the options in a spec file

describe "GET list" do  
  it "returns the list of questionnaires for the user" do  
    get :list  
    # ...  
  end
end

what I get when i run rspec is

Failures:

1) QuestionnairesController List GET list returns the list of questionnaires for the user
  Failure/Error: get :list
  No route matches {:controller=>"questionnaires", :action=>"list"}
  # ./spec/controllers/questionnaires_controller_spec.rb:20

The question is how do you write the spec file to pass the globbed parameters to rspec. I like to do something like this:

describe "GET list" do 
  it "returns the list of questionnaires for the user" do
    get :list, "/user/1/public/true/mine/true/shared/true"  
  end
end

and change the parameters to test the different cases


Solution

  • The globbing happens in the dispatcher, so the params are already assigned when the controller is invoked. When the controller action is reached, the globbed parameters should already be split into an array in params[:myparams].

    If you want to test this in the controller, just set up the params hash the way the dispatcher would:

    describe "GET 'list'" do
      it "should be successful" do
        get :list,  :myparams => "user/1/public/true/mine/true/shared/true".split("/")
        response.should be_success
      end
    end