Created
March 11, 2015 18:38
-
-
Save razorcd/b5d5a419eebe5dcff1bb to your computer and use it in GitHub Desktop.
Rspec custom matcher
This file contains hidden or 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/model_helpers.rb | |
# use like this: | |
# it { is_expected.to have_validation ValidDatePresenceValidator, | |
# :on => :start_date, | |
# :options => [:allow_blank, :allow_nil] | |
# } | |
RSpec::Matchers.define :have_validation do |validator, params| | |
match do |model| | |
my_validators = model.class.validators.select { |v| v.class == validator and v.attributes.include? params[:on] } | |
my_validators = validators.select { |v| params[:options].all? { |po| v.options.any? { |vo| vo == po } } } if params[:options] | |
my_validators.size == 1 | |
end | |
failure_message do |model| | |
message = "expected that #{model} would have validation #{validator} on '#{params[:on]}' field" | |
message = message + " and options '#{params[:options]}'" if params[:options] | |
message | |
end | |
failure_message_when_negated do |model| | |
message = "expected that #{model} would NOT have validation #{validator} on '#{params[:on]}' field" | |
message = message + " and options '#{params[:options]}'" if params[:options] | |
message | |
end | |
end | |
#TEST | |
#spec/models/validators/Rspec_support_model_helpers_spec.rb | |
require 'rails_helper' | |
describe "Rspec matchers" do | |
let(:test_model) do | |
Class.new do | |
include ActiveModel::Validations | |
attr_accessor :date_attr, :other_attr | |
validates :date_attr, valid_date_presence: true | |
end | |
end | |
subject { test_model.new } | |
describe "should have a functional 'have_validation' matcher" do | |
it { is_expected.to have_validation ValidDatePresenceValidator, :on => :date_attr } | |
it { is_expected.to_not have_validation ValidDatePresenceValidator, :on => :other_attr } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment