我是编程新手。现在,我正在使用rspec测试我的products_controller。该products_controller具有许多实例变量,其中一些实例使用“ where”方法来获取必要的数据。
我想知道如何在控制器中使用“ .where”和“ .where.not”来测试代码。
有人可以帮我吗?
models / 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
答案 0 :(得分:1)
例如,在您的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)