While working on the unit tests of Lele I had the situation where I wanted to differentiate among several validation errors a specific field might have.

Since I didn’t want to start comparing error messages contained in model.errors I came up with the following petit hack

For each validation error I cared about detecting (mostly the custom ones) I did the following…

inside say model Private.rb
def validate
  errors.add(:joined, "Run for your life!!!"+ercode(123)) if  grenade.released? 
end

Now what’s ercode(123) ? The argument is arbitrary, ercode is the following method monkey patch of ActiveRecord inside /config/initializer/application.rb

class ActiveRecord::Base
  def ercode(code)

    #turn an integer like '1' into a string like '01'
    str_code = (code <10 ? "0"+ code.to_s : code.to_s)    

    ENV['RAILS_ENV'] == "test" ?  str_code : "" # I only want this when testing
  end
end

Given this, inside private_test.rb I can check whether a particular validation has been triggered by detecting its error code inside the models error strings.

For example…

def test_custom_validations
  ...
  assert_error_code(private, 123)
end

def assert_error_code(model, code)
  assert model.errors.full_messages.join("").include?(code.to_s) # test wether too long left  
end

Sorry, comments are closed for this article.