Skip to content

Instantly share code, notes, and snippets.

@bohford
Created August 3, 2010 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bohford/506988 to your computer and use it in GitHub Desktop.
Save bohford/506988 to your computer and use it in GitHub Desktop.
An RSpec2 matcher for ActiveModel errors.
# Hey look, a matcher for RSpec2 that will check for an error on an ActiveModel attribute, given a I18n key and interpolation options.
#
# I feel like this should exist somewhere already, I am probably wrong though.
#
# @foo.should have_error_on(:bar, :bar_is_too_baz, :quux => :corge)
#
module RSpec
module Matchers
class HaveErrorOn
def initialize(attribute,key,options={})
@attribute = attribute
@key = key
@options = options
end
def matches?(actual)
@actual = actual
@expected_message = @actual.errors.generate_message(@attribute, @key, @options)
@actual.valid? # re-run validations
@actual.errors[@attribute].include?(@expected_message)
end
def failure_message_for_should
"expected #{@actual.inspect} to have error #{@key} on attribute #{@attribute}"
end
def failure_message_for_should_not
"expected #{@actual.inspect} to not have error #{@key} on attribute #{@attribute}"
end
def description
"have error #{@key} on attribute #{@attribute}"
end
end
def have_error_on(attribute,key,options={})
Matchers::HaveErrorOn.new(attribute,key,options)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment