FactoryGirl after_create method does not save

I have a simple situation setup to learn testing with FactoryGirl. The Bank has many transactions. Each time a transaction is created, it must subtract the transaction amount from the total amount of the bank.

Here is the code:

# Bank.rb - Has many transactions
class Bank < ActiveRecord::Base
  has_many :transactions
end


# Transaction.rb - Belongs to a bank and should decrement the bank 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 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

The test continues to fail, and the amount of the bank returns 1000 instead of the expected 750. I'm at a standstill!

+5
source share
1 answer

This test does not work because it bankis retrieved from the database and saved. The callback after_createmodifies the record in the database, but the object in bankdoes not see this and therefore is not updated.

You will need to call reloadon this object before checking the amount:

bank.reload
bank.amount.to_i.should == 750
+7

All Articles