aaandre
aaandre

Reputation: 2512

Custom Rails route test fails despite the route loading OK in the browser

I am getting an error testing a controller route despite being able to successfully load it via the browser. Rails4 + rspec.

Any ideas?

#controller spec 
describe PublicSitesController do

  describe "GET index" do
    it "returns success" do
      get :index                        #line 7 in the spec file
      response.status.should == 200
    end
  end

end


#routes
get ":site_name/:page_name", to: "public_sites#show"
get ":site_name", to: 'public_sites#index'
get "/", to: 'public_sites#root'


#controller
class PublicSitesController < ApplicationController

  def root
  end

  def index
  end

  def show
  end

end

#the error:
Failures:

1) PublicSitesController GET index returns success
   Failure/Error: get :index
   ActionController::UrlGenerationError:
     No route matches {:action=>"index", :controller=>"public_sites"}
   # ./spec/controllers/public_sites_controller_spec.rb:7:in `block (3 levels) in <top (required)>'

Here are the relevant routes via rake routes:

      GET    /:site_name/:page_name(.:format)                  public_sites#show
      POST   /:site_name/:page_name(.:format)                  public_sites#receive_form
      GET    /:site_name(.:format)                             public_sites#index
      GET    /                                                 public_sites#root

Upvotes: 0

Views: 574

Answers (1)

arieljuod
arieljuod

Reputation: 15838

You are missing some parameter on the request, the router doesn't know what to do with ":site_name", try something like:

get :index, site_name: 'something'

edit:

when you call get/post/etc inside a test you call the action name with that method, not the url, that way the controller test is independant of the url that make that action work (you can change the url and the controller will still work)

your route tells rails that it need some parameter named "site_name" so you need to tell rails what's inside "site_name" with a parameter for the action

if you want you can have routing tests, there you can test that some url goes to some controller's action with some value on some parameter https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/routing-specs

when you open the site on a browser you are not calling the action, you are actually running your whole application, then the routing system calls the controller's action

edit 2: if you want to test the show action you should call it with

get :show, site_name: 'some_site', page_name: 'some_page'

Upvotes: 1

Related Questions