I have a User model and a Shoppingcart model where
# user.rb
class User < ActiveRecord::Base
has_one :shoppingcart
end
and
# shopppingcart.rb
class Shoppingcart < ActiveRecord::Base
belongs_to :user
end
and I have this in routes.rb:
resources :users do
resource :shoppingcart
end
and in Shoppingcarts_controller.rb I have
class ShoppingcartsController < ApplicationController
def show
@user = User.find(current_user)
@shoppingcart = @user.build_shoppingcart
end
end
and within shoppingcarts_controller_test.rb:
require 'test_helper'
class ShoppingcartsControllerTest < ActionController::TestCase
def setup
@user = users(:michael)
end
test "should get show" do
puts(@user.name) # => Michael Example
puts(@user.id) # => 762146111
get :show # error line
assert_response :success
end
end
But when ever I run the test I get ActiveRecord::RecordNotFound: Couldn't find User with 'id'=. When I comment out the error line the error goes away and everything works. As for the non-test code, everything works. I can reach users/1/shoppingcart with no issue, so the problem must be coming from the test itself. How do I make a test for an action to a nested resource?
SessionsHelper.rb:
module SessionsHelper
# Returns the current logged-in user (if any).
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
@current_user = user
end
end
end
end
findmethod requires primary key of the particular user fromUserstable, not the user itself. Primary key isid, so you need to change this line in your controller.