我正在记录财务Interactions
,建模为偶数,LedgerEntries
并且每个Interaction
总和必须为零。
class Interaction < ActiveRecord::Base
has_many :entries, class_name: 'LedgerEntry'
validate :entries_must_sum_to_zero
def balance
credit = self.entries.sum(:credit)
debit = self.entries.sum(:debit)
return credit - debit
end
protected
def entries_must_sum_to_zero
if self.entries.count.odd?
errors.add(:entries, "There must be an even number of entries.")
end
if self.balance != 0
errors.add(:entries, "Entries must sum to zero.")
end
end
end
和
class LedgerEntry < ActiveRecord::Base
validates_numericality_of :credit, greater_than_or_equal_to: 0
validates_numericality_of :debit, greater_than_or_equal_to: 0
belongs_to :interaction
validate :one_of_credit_or_debit
protected
def one_of_credit_or_debit
if self.credit != 0 && self.debit != 0
errors.add(:credit, "You can't assign both a credit and debit to the one entry.")
end
end
end
我遇到的问题是这个测试永远不会失败。
it "should complain if an Interaction's balance is non-zero" do
d = LedgerEntry.create!(credit: 50.0)
expect {Interaction.create!(entries: [d])}.to raise_error ActiveRecord::RecordInvalid
end
在执行期间entries_must_sum_to_zero
self.entries.count
始终为 0 并self.balance
始终返回 0。
如何在验证方法运行之前强制使用条目?