Skip to content

Instantly share code, notes, and snippets.

@macedo
Created June 28, 2012 19:49
Show Gist options
  • Save macedo/3013447 to your computer and use it in GitHub Desktop.
Save macedo/3013447 to your computer and use it in GitHub Desktop.
RSpec matcher to test validations and error messages
RSpec::Matchers.define :have_errors_on do |attribute, *values|
@attribute = attribute
@values = values
@failed = []
match_for_should do |record|
@record = record
matches_against?(true)
end
match_for_should_not do |record|
@record = record
matches_against?(false)
end
def matches_against?(compare)
@values.each do |value|
@record.__send__("#{@attribute}=", value)
@record.valid?
@failed << value if @record.errors[@attribute].empty? == compare
end
if @message
@failed.empty? && @record.errors[@attribute].include?(@message)
else
@failed.empty?
end
end
failure_message_for_should do |model|
if @message
"expected #{@record.inspect} to have #{@message.inspect} error message for each of #{@values.inspect} on #{@attribute.inspect} (didn't accept #{@failed.inspect})"
else
"expected #{@record.inspect} to have errors for each of #{@values.inspect} on #{@attribute.inspect} (didn't accept #{@failed.inspect})"
end
end
failure_message_for_should_not do |model|
"expected #{@record.inspect} to haven't errors for each of#{@values.inspect} on #{@attribute.inspect} (accepted #{@failed.inspect})"
end
chain :with_message do |message|
@message = message
end
description do
if @message
"have errors for #{values.inspect} on #{@attribute} with message #{@message.inspect}"
else
"have errors for #{values.inspect} on #{@attribute}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment