0
votes

I've got routes setup so that they work as expected in my controllers; I can use both room_path and rooms_path as expected.

However when I try to use the same routes in a controller spec for some reason then I get an error:

ActionController::UrlGenerationError: No route matches {:action=>"/1", :controller=>"rooms"}

My routes.rb file:

  root "rooms#index"
  resources :rooms, :path => '/', only: [:index, :create, :show] do 
    resources :connections, only: [:create,:destroy]
  end

And if I rake routes:

room_connections POST   /:room_id/connections(.:format)     connections#create
room_connection DELETE  /:room_id/connections/:id(.:format) connections#destroy
rooms GET    /              rooms#index
      POST   /              rooms#create
room  GET    /:id(.:format) rooms#show

However my test fails:

describe "GET room_path(room)" do
    it "renders show" do
      @room = Room.create
      get room_path(@room)
      expect(response.status).to eq(200)
      expect(response).to render_template(:show)
    end
end

While my controllers can use the same route helpers without issue:

class RoomsController < ApplicationController
  def index
  end

  def create
    @room = Room.create
    redirect_to room_path(@room)
  end

  def show
    @room = Room.find(params[:id])
  end
end

I'm not sure why in my tests it seems to go looking for a "/1" action rather than rooms#show like I would expect.

Update

So continuing to play this I've been able to get the test green by changing to the following:

describe "GET room_path(room)" do
    it "renders show" do
      @room = Room.create
      get :show, params: { id: @room.id }
      expect(response.status).to eq(200)
      expect(response).to render_template(:show)
    end
 end

I would still love to understand why my helpers aren't working though. Is this to be expected? Manually writing the Parameters hash is kind of a PITA.

1

1 Answers

0
votes

I don't know what version of Rails and RSpec you're on. This works for me on Rails 4.2 and Rspec 3.4.4:

describe "my neat test description", type: :routing do
  it "can use path helper" do
    puts whatever_path
  end
end

The type: :routing pulls in the path and url helpers.

I believe the reason you don't have that by default is that rspec is replicating a lot of the environment for the different types of tests. For controller tests, it's pulling in the various path and url helpers because generally speaking they're used there often enough to be worth pulling in. In model tests, for example, they aren't used there often so they aren't pulled in by default.

These helpers live on the app object.