ruby-on-rails - 如何在控制器中使用“.where”和“.where.not”方法测试实例变量
问题描述
我是编程新手。现在,我正在使用 rspec 测试我的 products_controller。这个 products_controller 有许多实例变量,其中一些使用“where”方法来获取必要的数据。
我想知道如何在控制器中使用“.where”和“.where.not”测试代码。
有人可以帮助我吗?
模型/product.rb(关联提取)
belongs_to :category, optional: true
belongs_to :user
has_many :product_images
accepts_nested_attributes_for :product_images
products_controller.rb
def show
@product = Product.find(params[:id])
@images = @product.product_images.limit(4)
@products = @product.user.products.where.not(id: params[:id]).limit(6)
@category_products = Product.where(category_id:@product.category).where.not(id: params[:id]).limit(6)
@prev_item = @product.showPrevItem if @product.checkPrevItem
@next_item = @product.showNextItem if @product.checkNextItem
end
products_controller.spec.rb
FactoryBot.define do
factory :product do
name {'アメリカンイーグルのTシャツ'}
description {'買ったばっかり'}
category_id {'1'}
size {'M'}
product_status {'新品、未使用'}
delivery_fee {'着払い'}
local {'北海道'}
lead_time {'1~2日で発送'}
price {'300'}
transaction_status {'出品中'}
user
category
end
end
products_controller_spec.rb(不完整)
require 'rails_helper'
describe ProductsController, type: :controller do
describe 'GET #show' do
it "renders the :show template" do
product = create(:product)
get :show, params: { id: product }
expect(response).to render_template :show
end
it "assigns the requested product to @product" do
product = create(:product)
get :show, params: {id:product}
expect(assigns(:product)).to eq product
end
it "populates an array of products" do
product = create(:product)
user = product.user
products = create_list(:product, 3)
end
end
end
解决方案
例如,在您的products
工厂中,您可以通过关联来创建具有相同用户的所有产品:
product = create(:product)
user = product.user
products = create_list(:product, 3, user: user)
然后你可以测试一些你认为相关的事情,比如关系的存在:
get :show, params: { id: product }
expect(assigns(:products).size).to eq 3
查询的限制:
products = create_list(:product, 10, user: user)
get :show, params: { id: product }
expect(assigns(:products).size).to eq 6
不包含产品:
get :show, params: { id: product }
expect(assigns(:products)).not_to include(product)
推荐阅读
- python - 在 Python 应用程序中使用 Raspberry Pi 4B 终端命令
- flutter - Flutter web 是否有 AdMob 支持?
- python - 如何使用 Google docs API Python 检索部分 ID
- java - Flutter 无法获取输出图像或标签显示?我错过了什么?
- java - 如何使 constrictor 方法不具有破坏性?
- java - JDA 多监听器
- azure-monitoring - Azure 存储队列指标的更新频率如何?
- rust - 为实现具有关联生命周期的特征的泛型类型实现特征时的生命周期问题
- url - 服务器端重定向后如何保留 URL 片段?
- visual-studio-code - 无法使用 Vscode ssh 连接到 google dl 平台