Search code examples
ruby-on-railstestingrspecrecord

ActiveRecord::RecordNotFound:


Im testing my app with rspec with the next simple code:

require 'spec_helper'

    describe CarsController do
    describe "GET 'new'" do
            it "should be successful" do
            visit new_user_car_path(:user_id=>"28")
            response.should be_success
            end
        end
    end

when I run it I got this message

Failure/Error: visit new_user_car_path(:user_id=>"28")
 ActiveRecord::RecordNotFound:
   Couldn't find User with id=28
 # ./app/controllers/cars_controller.rb:3:in `new'
 # ./spec/controllers/tanking_logs_controller_spec.rb:6:in `block (3 levels) in <top (required)>'

I don't know whats happens with this, in my routes appears the new_user_car_path, look...

user_cars GET    /users/:user_id/cars(.:format)                               cars#index
                      POST   /users/:user_id/cars(.:format)                               cars#create
         new_user_car GET    /users/:user_id/cars/new(.:format)                           cars#new
        edit_user_car GET    /users/:user_id/cars/:id/edit(.:format)                      cars#edit
             user_car GET    /users/:user_id/cars/:id(.:format)                           cars#show
                      PUT    /users/:user_id/cars/:id(.:format)                           cars#update
                      DELETE /users/:user_id/cars/:id(.:format)                           cars#destroy

and this is my routes.rb if it needs

Estaciones::Application.routes.draw do
root :to => "static_pages#home"
match '/contact', :to=>'static_pages#contact'
match '/about', :to=>'static_pages#about'
devise_for :users
resources :gas_stations
   resources :users do
      resources :cars do
      #resources :tanking_logs
      end
   end
...

Solution

  • new_user_car GET    /users/:user_id/cars/new(.:format)
    

    Your path needs a :user_id param in order to work, and you're not providing one.

    EDIT As per your comments, if you're using Factory Girl Rails you can set up a factory to create users, and then do something like:

    user = Factory.create :user
    visit new_user_car_path(:id => user.id)
    

    Else, you can manually create them:

    user = User.create!(:name => "Joe", ...)
    visit new_user_car_path(:id => user.id)