首页 > 解决方案 > 如何在控制器中使用“.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

标签: ruby-on-railsruby

解决方案


例如,在您的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)

推荐阅读