Question

I'm having a problem with counter_cache. Say I have three models. User and Article have many ArticleUpvotes. User can create ArticleUpvote for an article.

User

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

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

Article

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

ArticleUpvote

# 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 

Failing test

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

Error

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

   expected: 1
        got: 0

   (compared using ==)

Passing tests

Just changing my test body to:

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

Or doing this:

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

Makes tests pass. Why is this happening?

Was it helpful?

Solution

Change your example as below:

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

The reason why your given example failed was that the spec was holding the article object which was created via FactoryGirl using FactoryGirl.create(:article) and it does not know that there was a change made in the database. You will need to reload the article so that the change gets reflected.

In other passing test,i.e.,

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

your example passes because an implicit reload happens because of change method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top