Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RSpec matcher for validates_with
# RSpec matcher for validates_with.
# https://gist.github.com/2032846
# Usage:
#
# describe User do
# it { should validate_with CustomValidator }
# end
RSpec::Matchers.define :validate_with do |expected_validator, options|
match do |subject|
@validator = subject.class.validators.find do |validator|
validator.class == expected_validator
end
@validator.present? && options_matching?
end
def options_matching?
if @options.present?
@options.all? { |option| @validator.options[option] == @options[option] }
else
true
end
end
chain :with_options do |options|
@options = options
end
description do
"RSpec matcher for validates_with"
end
failure_message do |text|
"expected to validate with #{validator}#{@options.present? ? (' with options ' + @options) : ''}"
end
failure_message_when_negated do |text|
"do not expected to validate with #{validator}#{@options.present? ? (' with options ' + @options) : ''}"
end
end
@rdh
Copy link

rdh commented Jul 30, 2017

Just FYI, I've included this in my personal gem of spec helpers ... https://github.com/schrodingersbox/spec_cat#credits ... please open an issue if you object or would like any changes to the attribution.

And thanks!

@pcrglennon
Copy link

pcrglennon commented Aug 23, 2017

Thanks for writing this up!

I just used this and noticed that it wasn't actually checking the values of options against the options passed to the Validator. So I forked it to fix that, and expand upon it a bit more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment