這是我的模型 'Order' 和 'Order_item' 模型與它有關聯
class Order < ApplicationRecord
has_many :order_items
belongs_to :user
before_save :set_subtotal
def subtotal
order_items.collect { |order_item| order_item.valid? ? order_item.unit_price * order_item.quantity : 0 }.sum
end
private
def set_subtotal
self[:subtotal] = subtotal
end
end
第二個模型:
class OrderItem < ApplicationRecord
belongs_to :product
belongs_to :order
before_save :set_unit_price
before_save :set_total
def unit_price
# If there is a record
if persisted?
self[:unit_price]
else
product.price
end
end
def total
return unit_price * quantity
end
private
def set_unit_price
self[:unit_price] = unit_price
end
def set_total
self[:total] = total * quantity
end
end
我正在嘗試檢查 RSPEC 的測驗用例中的 'SUbtotal' 函式,但我似乎找不到邏輯
Rspec 模型檔案:訂購
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Order, type: :model do
let(:user) { FactoryBot.create(:user) }
let(:subtotal) { FactoryBot.create(:order, subtotal: 1000) }
let(:items) { FactoryBot.create(:order_item) }
describe 'callbacks' do
it { is_expected.to callback(:set_subtotal).before(:save) }
end
describe 'associations' do
it { is_expected.to belong_to(:user) }
it { is_expected.to have_many(:order_items) }
end
#Gives Error i dont know how to get this
# describe 'subtotal' do
# it 'it should calculate the subtotal' do
# expect(Order.subtotal).to eq(1000)
# end
# end
end

uj5u.com熱心網友回復:
看起來您正在嘗試呼叫該類的實體方法。如果您更改為在實體上呼叫 subtotal,您將看到不同的錯誤。
Order.new.subtotal
應該有這個定義。
為了讓您的電話在規范中作業,您需要在類上定義的方法self。
def self.subtotal
...
end
uj5u.com熱心網友回復:
就像@nikkypx 已經說過你在類本身上呼叫一個實體方法一樣。
在您的測驗設定中,您創建了一個名為的 Order 實體subtotal。因此,要使其正常作業,您必須將測驗更改為:
expect(subtotal.subtotal).to eq(1000)
現在,由于您將實體命名為時髦,這聽起來令人困惑。更合乎邏輯的是命名 Order 實體order。
let(:order) { FactoryBot.create(:order, subtotal: 1000) }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/524670.html
