1

我有两个简单的类CompanyVotings我用 rspec 测试它们。

当我向公司添加投票时,它会被 activeRecord 计算在内

class Company < ActiveRecord::Base
  attr_accessible :name, :votings_count
  has_many :votings, :dependent => :destroy
end

这个投票类:

class Voting < ActiveRecord::Base
  attr_accessible :percent, :company, :company_id

  belongs_to :company, counter_cache: true
end

和这个简单的 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 ==)

该列不为零。默认 = 0

add_column :companies, :votings_count, :integer, default: 0

我遵循了 ryans counter_cache cast -> http://railscasts.com/episodes/23-counter-cache-column?view=asciicast中的示例

数据库计数正确,但实例未更新。

我有错误的设置吗?为什么会这样?

非常感谢!

4

1 回答 1

0

您需要重新加载实例以反映 db 中的更改。

# ...
c.save
c.votings.create(Fabricate.attributes_for :voting)
# Add this line
c.reload
c.votings_count.should == 1
于 2013-09-24T13:10:10.127 回答