Rake test and validates_inclusion_of


#1

Hello,

I am just starting off with Rails, so I apologize in advance if there
is a terribly obvious answer to my problem. I’ve done some searching
and found similar problems to my own, but nothing which yielded a
solution.

I have a handful of models that I am unit testing. The tests for each
unit run successfully, but when I do a rake test, many of the tests
fail.

The assertions that fail are always ones that are asserting that a
model, which has a reference to another model, is OK. So for example,
one assertion that passes when I do ruby test/unit/department_test.rb, but fails when I do rake test is:

department = Department.new(:name => “super department”,
:parent_id => departments(:administration_department).id)
assert department.save

When I print out department.errors, I see that parent_id is invalid
because it “is not included in the list”.

The validation I have on parent_id is:

validates_inclusion_of :parent_id, :in => Department.find_all.collect {
|e| e.id }

So, maybe the department table wasn’t the best example because it’s
acts_as_tree, BUT all the failed assertions are the same:

  • they’re failing on asserting that an object is good
  • the object has a reference to another model
  • that reference is being validated with validates_inclusion_of
  • that reference never passes validation
  • they pass when i run the test script individually

So my hypothesis is that the fixture data isn’t being loaded in before
the constraints for the reference_id are being defined, but ONLY in the
rake test environment.

Does that make sense? Am I missing something obvious? Any thoughts
would be appreciated.

I’m using Rails 1.1.6 and MySQL (with no foreign key constrains in the
DB).

Thanks,
Julia


#2

Well, I got no responses to this post explaining why this happens, but
I did work around this issue.

For future reference, in case anyone else has this problem, I fixed the
rake test errors by validating the reference ID in the validate
function instead of using validates_inclusion_of.

So, I removed this:

validates_inclusion_of :parent_id, :in => Department.find_all.collect {
|e| e.id }

… and replaced it with this:

protected
def validate
unless Department.exists?(parent_id)
errors.add(:parent_id, “is not a valid department”)
end
end

Julia


#3

I was having the same problem just the other day, this solution worked
but I ended up using
validates_associated.

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000948