"should get show" 嵌套资源的控制器测试失败
"should get show" controller test failing for Nested resource
我有一个 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
find
方法需要来自 Users
table 的特定用户的主键,而不是用户本身。主键是 id
,因此您需要在控制器中更改此行。
@user = User.find(params[:user_id])
我有一个 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
find
方法需要来自 Users
table 的特定用户的主键,而不是用户本身。主键是 id
,因此您需要在控制器中更改此行。
@user = User.find(params[:user_id])