You need to reload the instance to reflect the changes in db.
# ...
c.save
c.votings.create(Fabricate.attributes_for :voting)
# Add this line
c.reload
c.votings_count.should == 1
Question
I have two simple classes Company
and Votings
which I test with rspec.
When I add a voting to a company it gets counted by an activeRecord
class Company < ActiveRecord::Base
attr_accessible :name, :votings_count
has_many :votings, :dependent => :destroy
end
and this voting class:
class Voting < ActiveRecord::Base
attr_accessible :percent, :company, :company_id
belongs_to :company, counter_cache: true
end
and this simple rspec
require 'spec_helper'
describe Company do
it "should count the votings in a table" do
c = Company.new(Fabricate.attributes_for :company)
c.save
c.votings.create(Fabricate.attributes_for :voting)
c.votings_count.should == 1
end
end
#expected: 1
#got: 0 (using ==)
the column is not nil. Default = 0
add_column :companies, :votings_count, :integer, default: 0
I've followed the example from ryans counter_cache cast -> http://railscasts.com/episodes/23-counter-cache-column?view=asciicast
The DB is counted correctly, but the instance is not updated.
Do I have a wrong setup? Why do this behave like this?
many thanks!
Solution
You need to reload the instance to reflect the changes in db.
# ...
c.save
c.votings.create(Fabricate.attributes_for :voting)
# Add this line
c.reload
c.votings_count.should == 1