Created
March 31, 2014 01:05
-
-
Save tristang/9883141 to your computer and use it in GitHub Desktop.
Tests for counter_cache when option is not given
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest/autorun' | |
require 'logger' | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
ActiveRecord::Schema.define do | |
create_table :posts do |t| | |
t.integer :comments_count, default: 0 | |
end | |
create_table :comments do |t| | |
t.integer :post_id | |
end | |
end | |
class Post < ActiveRecord::Base | |
# No counter_cache | |
has_many :comments | |
end | |
class Comment < ActiveRecord::Base | |
belongs_to :post | |
end | |
class BugTest < Minitest::Test | |
def test_counter_cache_assuming_option_is_required | |
post = Post.create! | |
post.comments << Comment.create! | |
# comments_count is not incremented, because counter_cache option was not given | |
assert_equal 0, post.comments_count | |
post.comments.destroy_all | |
# comments_count should not be decremented, because counter_cache option was not given | |
assert_equal 0, post.comments_count | |
end | |
def test_counter_cache_works_assuming_option_is_not_required | |
post = Post.create! | |
post.comments << Comment.create! | |
# comments_count should be incremented, because a comments_count column is present | |
assert_equal 1, post.comments_count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment