Forked from otaviomedeiros/validate_with_matcher.rb
Last active
August 17, 2023 14:15
-
-
Save Bartuz/98abc9301adbc883b510 to your computer and use it in GitHub Desktop.
RSpec matcher for validates_with
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 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 |
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
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!