Tech Journal Back to Tech Journal

I get a nil object when running a rake test in Rails, but it doesn't happen when I just run the test manually!

Here's a scenario:

There are 2 models: Course and CoursePage.
CoursePage :belongs_to Course.

During testing, when I create a CoursePage instance from a fixture using:

t = course_pages(:fixture_name)

And then do:

c = t.course

I get a nil object!

But this only happens when I run the test using rake or rake test:units.
When I run the test using ruby test/unit/course_page.rb, it runs fine!

Well, the reason that running through rake fails is that rake runs rake tests which runs off of your test-db, and not your development-db, which is what happens when you run it using ruby. There's no data in your test-db. You can furnish the data using fixtures for courses, specified just like the fixtures for course_pages:

fixtures :courses, :course_pages

Please note how courses preceeds course_pages. You have to make sure that the CoursePage instances in the course_pages fixtures have a course_id that exists in the courses fixture. Everything should work, then - Simply because the test-db is populated.

Last updated on 2008-01-01 06:01:33 -0700, by Shalom Craimer

Back to Tech Journal