我有一个简单的情境设置,以便学习FactoryGirl的测试。 银行有很多交易。每次创建交易时,都应从银行的总额中减去交易金额。
以下是代码:
# Bank.rb - Has many transactions
class Bank < ActiveRecord::Base
has_many :transactions
end
# Transaction.rb - Belongs to a bank and should decrement the bank's total when created.
class Transaction < ActiveRecord::Base
belongs_to :bank
after_create :decrement_bank_amount
def decrement_bank_amount
bank.decrement!(:amount, amount) if bank
end
end
# factories.rb - Create default factories for testing. This is FactoryGirl 4 syntax
FactoryGirl.define do
factory :bank do
sequence(:name) { |n| 'Bank ' + n.to_s }
end
factory :transaction do
sequence(:title) { |n| 'Payment ' + n.to_s }
bank
end
end
# Transaction_spec.rb - Creates a bank and a transaction.
require 'spec_helper'
describe Transaction do
describe ".create" do
context "when a bank is set" do
it "decreases the bank's amount" do
bank = FactoryGirl.create(:bank, :amount => 1000) do |b|
b.transactions.create(:amount => 250)
end
bank.amount.to_i.should eq 750
end
end
end
end
测试一直失败,银行金额不断返回 1000 而不是预期的 750 。我很难过!
答案 0 :(得分:7)
此测试失败,因为从数据库中提取bank
并存储。 after_create
回调会修改数据库中的记录,但bank
中的对象看不到,因此不会更新。
在检查金额之前,您需要在该对象上调用reload
:
bank.reload
bank.amount.to_i.should == 750