Created
August 17, 2011 09:59
-
-
Save amatsuda/1151239 to your computer and use it in GitHub Desktop.
An RSpec matcher for asserting AR query
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
RSpec::Matchers.define :query do |query_hash| | |
match do |relation| | |
@failed = [] | |
query_hash[:where].each do |k, v| | |
@failed << :where if relation.where_values_hash[k] != v | |
end if query_hash.has_key? :where | |
if query_hash.has_key? :order | |
@failed << :order unless query_hash[:order].in? relation.order_values | |
end | |
if query_hash.has_key? :limit | |
@failed << :limit unless query_hash[:limit] == relation.limit_value | |
end | |
if query_hash.has_key? :offset | |
@failed << :offset unless query_hash[:offset] == relation.offset_value | |
end | |
@failed.none? | |
end | |
failure_message_for_should do |model| | |
"expected #{@failed.inspect} to query #{query_hash.inspect}" | |
end | |
end |
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 'spec_helper' | |
describe User do | |
subject { User.where(:name => 'foo').where('age > 20').order('created_at desc').order('id desc').limit(10).offset(30) } | |
it { should query :where => {:name => 'foo'} } | |
it { should query :where => {:name => 'bar'} } | |
it { should query :order => 'id desc' } | |
it { should query :limit => 30 } | |
it { should query :offset => 30 } | |
end |
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
% rspec spec/models/user_spec.rb | |
.F.F. | |
Failures: | |
1) User | |
Failure/Error: it { should query :where => {:name => 'bar'} } | |
expected [:where] to query {:where=>{:name=>"bar"}} | |
# ./spec/models/user_spec.rb:6 | |
2) User | |
Failure/Error: it { should query :limit => 30 } | |
expected [:limit] to query {:limit=>30} | |
# ./spec/models/user_spec.rb:8 | |
Finished in 0.01415 seconds | |
5 examples, 2 failures |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment