0

我遇到了问题counter_cache。假设我有三个模型。User 和 Article 有很多 ArticleUpvotes。用户可以为文章创建 ArticleUpvote。

用户

# models/user.rb
class User < ActiveRecord::Base
  has_many :upvotes, class_name: 'ArticleUpvote'

  def upvote(article)
    article.upvotes.create(user: self)
  end
end

文章

# models/article.rb
class Article < ActiveRecord::Base
  has_many :upvotes, class_name: 'ArticleUpvote'
end

文章支持

# models/article_upvote.rb
class ArticleUpvote < ActiveRecord::Base
  include ArticleVote

  belongs_to :article, dependent: :destroy, counter_cache: :upvotes_count
end

# models/concerns/article_vote
module ArticleVote
  extend ActiveSupport::Concern

  included do
    belongs_to :user

    validates :user, presence: true
  end
end 

失败的测试

context 'voting' do
  let(:user) { FactoryGirl.create(:user) }
  let(:article) { FactoryGirl.create(:article) }

  context '#upvote' do
    it 'adds upvote to article' do
      user.upvote(article)
      expect(article.upvotes.size).to eq 1
    end
  end
end

错误

1) User voting #upvote adds upvote to article
 Failure/Error: expect(article.upvotes.size).to eq 1

   expected: 1
        got: 0

   (compared using ==)

通过测试

只需将我的测试机构更改为:

user.upvote(article)
article.upvotes.size # Added this line compared to failing version
expect(article.upvotes.size).to eq 1

或者这样做:

expect{ user.upvote(article) }.to change{ article.upvotes.size }.by 1

使测试通过。为什么会这样?

4

1 回答 1

1

如下更改您的示例:

it 'adds upvote to article' do
  user.upvote(article)
  expect(article.reload.upvotes.size).to eq 1
end

您给定示例失败的原因是规范持有通过usingarticle创建的对象,并且它不知道数据库中发生了更改。您将需要该文章,以便反映更改。FactoryGirlFactoryGirl.create(:article)reload

在其他通过测试中,即

expect{ user.upvote(article) }.to change{ article.upvotes.size }.by 1 

您的示例通过了,因为由于change方法而发生了隐式重新加载。

于 2014-04-04T21:13:53.687 回答