【问题标题】:Rspec test case for model模型的 Rspec 测试用例
【发布时间】:2021-02-03 06:25:20
【问题描述】:

我有 line_item.rb

class LineItem < ApplicationRecord
  belongs_to :product, optional: true
  belongs_to :cart
  belongs_to :order, optional: true


  def total_price
    product.price * quantity.to_i
  end
end

编写的测试用例

require 'rails_helper'

RSpec.describe LineItem, type: :model do
  describe '#total_price' do
    let!(:user) { create(:user) }
      it 'this is for the total function' do
        # product = build(:product)
        # lineitem = build(:line_item)     
        category = create(:category)
        product = create(:product, category_id: category.id)   
        order = create(:order, user_id: user.id, email: user.email)
        cart = create(:cart)
        line_item = create(:line_item,order_id: order.id,product_id: product.id,cart_id:cart.id)
        res = product.price * line_item.quantity.to_i
        expect(res.total_price).to eq(10)
      end
  end
  
end

我无法为 total_price 编写测试用例。谁能告诉我 谢谢

【问题讨论】:

    标签: ruby-on-rails rspec ruby-on-rails-5 rspec-rails rspec3


    【解决方案1】:

    您应该在 LineItem 对象上调用 total_price

    category = create(:category)
    product = create(:product,
      category_id: category.id,
      price: 2000) # in cents   
    order = create(:order,
      user_id: user.id,
      email: user.email)
    cart = create(:cart)
    line_item = create(:line_item,
      order_id: order.id,
      product_id: product.id,
      cart_id:cart.id,
      quantity: 2)
    
    expect(line_item.total_price).to eq(4000)
    

    一件小事。 line_items 表上的 quantity 字段应该是一个数字。因此,您不需要多余的to_i 调用。

    def total_price
      product.price * quantity
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      相关资源
      最近更新 更多