简体   繁体   中英

Rspec test case for model

I have 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

test case written

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

I am unable to write the test case for total_price. Could anyone let me know Thank you

You should call total_price on the LineItem object.

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)

A minor thing. The quantity field on the line_items table should be a number. So, you don't need the superfluous to_i call.

def total_price
  product.price * quantity
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM