Last active
August 29, 2015 14:00
-
-
Save joeyates/9600a604356417187513 to your computer and use it in GitHub Desktop.
hash_matching: an RSpec arguments matcher like hash_including, but which handles Regexps
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
# spec/support/custom_argument_matchers.rb | |
module CustomArgumentMatchers | |
class HashMatching | |
attr_reader :expected | |
def initialize(expected) | |
@expected = expected | |
end | |
def ==(target) | |
expected.each do |key, matcher| | |
return false unless target.include?(key) | |
if matcher.is_a?(Regexp) | |
return false unless target[key].match(matcher) | |
next | |
end | |
return false unless target[key] == matcher | |
end | |
true | |
end | |
def inspect | |
"a Hash with elements matching #{expected.inspect}" | |
end | |
end | |
def hash_matching(expected) | |
HashMatching.new(expected) | |
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
describe 'foos' do | |
it 'calls a method' do | |
expect(bar).to have_received(:baz).with(hash_matching(quux: 'Hi', fnord: /hi/)) | |
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
# spec/spec_helper.rb | |
RSpec.configure do |config| | |
config.include CustomArgumentMatchers | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment