我有一个User
模型和一个Shoppingcart
模型
# user.rb
class User < ActiveRecord::Base
has_one :shoppingcart
end
和
# shopppingcart.rb
class Shoppingcart < ActiveRecord::Base
belongs_to :user
end
我在routes.rb中有这个:
resources :users do
resource :shoppingcart
end
并且在Shoppingcarts_controller.rb中我有
class ShoppingcartsController < ApplicationController
def show
@user = User.find(current_user)
@shoppingcart = @user.build_shoppingcart
end
end
并在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
但是当我进行测试时,我得到了ActiveRecord::RecordNotFound: Couldn't find User with 'id'=
。当我注释掉错误行时,错误消失了,一切正常。至于非测试代码,一切正常。我可以毫无问题地到达users/1/shoppingcart
,因此问题必须来自测试本身。如何对嵌套资源的操作进行测试?
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
答案 0 :(得分:1)
find
方法需要来自Users
表的特定用户的主键,而不是用户本身。主键为id
,因此您需要在控制器中更改此行。
@user = User.find(params[:user_id])