[rspec-users] Rails validation spec fails (but code works in development env)

Gintautas S. lists at ruby-forum.com
Wed Jul 4 08:24:56 UTC 2012

I came across the same issue. I was trying to accomplish exactly the 
same thing like the original poster (make sure that association is with 
an actual record in the DB). I came across the same issue too, and after 
a little debugging the core the solution is to use Proc.

This has to do with loading mechanics, IMO: when you run the spec, first 
the model definition is loaded, there are no records in the DB yet, so 
:in option is just empty array (I debugged this to be true). But if you 
use Proc in that place, then the query to get records from DB is 
executed "lazily"; by that time your spec has correct context setup 
(manufacturers table populated) and thus you get correct behavior from 

In your case you should use:

validates :manufacturer_id, :inclusion => {
  :in => Proc.new { Manufacturer.all.collect { |m| m.id } }

Posted via http://www.ruby-forum.com/.

More information about the rspec-users mailing list