Skip to content

Commit

Permalink
Merge pull request #143 from 90yukke/counter-cache-matcher
Browse files Browse the repository at this point in the history
Add with_counter_cache relation matcher's option
  • Loading branch information
rodrigopinto committed Jan 29, 2015
2 parents 19b7479 + 7c90054 commit deb3057
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -85,7 +85,7 @@ RSpec.describe Record do
end

RSpec.describe Site do
it { is_expected.to have_many(:users).as_inverse_of(:site).ordered_by(:email.asc) }
it { is_expected.to have_many(:users).as_inverse_of(:site).ordered_by(:email.asc).with_counter_cache }
end
```

Expand Down
15 changes: 15 additions & 0 deletions lib/matchers/associations.rb
Expand Up @@ -101,6 +101,12 @@ def with_foreign_key(foreign_key)
self
end

def with_counter_cache
@association[:counter_cache] = true
@expectation_message << " which specifies counter_cache as #{@association[:counter_cache].to_s}"
self
end

def matches?(actual)
@actual = actual.is_a?(Class) ? actual : actual.class
metadata = @actual.relations[@association[:name]]
Expand Down Expand Up @@ -235,6 +241,15 @@ def matches?(actual)
end
end

if @association[:counter_cache]
if metadata.counter_cached? != true
@negative_result_message = "#{@positive_result_message} which did not set counter_cache"
return false
else
@positive_result_message = "#{@positive_result_message} which set counter_cache"
end
end

return true
end

Expand Down
4 changes: 2 additions & 2 deletions spec/models/site.rb
Expand Up @@ -3,7 +3,7 @@ class Site

field :name

has_many :users, inverse_of: :site, order: :email.desc
has_many :users, inverse_of: :site, order: :email.desc, counter_cache: true

validates :name, presence: true, uniqueness: true
end
end
2 changes: 1 addition & 1 deletion spec/unit/associations_spec.rb
Expand Up @@ -37,6 +37,6 @@
end

describe Site do
it { is_expected.to have_many(:users).as_inverse_of(:site).ordered_by(:email.desc) }
it { is_expected.to have_many(:users).as_inverse_of(:site).ordered_by(:email.desc).with_counter_cache }
end
end

0 comments on commit deb3057

Please sign in to comment.