Austin Ruby On Rails Developer Blog

Mongoid + Test::Unit + Shoulda Matchers

Trying to do validates_presence_of with a Rails 3 app running Mongoid, Test::Unit, and Shoulda?

You might be in for a bit of pain.

Have no fear! Here’s a quick fix that might help you out:

In your Gemfile, be sure to explicitly add both lines:

gem "shoulda"
gem "shoulda-matchers"

Apparently there is some issue where just installing ‘shoulda’ doesn’t give you the matchers on a non-ActiveRecord app, even though they (mostly) should work ActiveModel and Mongoid.

UPDATE: another solution here is to just use the beta version of shoulda, if you’re so inclined:
gem “shoulda”, “>=3.0.0.beta2”

Published on Wed, 11 Jan 2012 21:33

ActiveRecord Validation Dependencies

If you need to add some custom validation for an ActiveRecord model beyond using the standard validation helpers, there are some things to consider.

For custom validation implement the method inside your ActiveRecord class:

 def more_validation #some validation code end 

One of the issues I had was I had an attribute not set by the form submission. In this case it was the endtime attribute. Note starttime and endtime are defined in the Event ActiveRecord model.

 class Event < ActiveRecord validates_numericality_of :duration validate :more_validation, :if => {|a| a.duration} def before_save self.endtime = starttime + duration.minutes end def more_validation endtime = starttime + duration.minutes # duration has been validated so this is ok # do some more validation end end 

I set my attribute in the before_save callback. This code will execute only if validation passes.
Make sure before_save doesn't return boolean false as request chain will be halted if a before_filter returns false.

Some use validation callbacks

  • after_validation() After all validation procedures are complete
  • after_validation_on_create() After validation of new objects
  • after_validation_on_update() After validation of existing objects being updated
  • before_validation() Before the object is validated
  • before_validation_on_create() Before validation of new objects
  • before_validation_on_update() Before validation of existing objects being updated

It should be noted, the code in the above validation methods will always be executed REGARDLESS if previous validation method calls have failed or not unless we place a conditional Proc that checks for dependencies. So this is how you can have validation code that depends on other validation like a form validation helper validates_presence_of.

Published on Thu, 09 Dec 2010 14:28