Thursday, December 13, 2007

rSpec and Relationships

I spend a good 3 hours figuring out why my spec tests were failing. Let me explain my scenario to you.


My scenario was pretty much like this: Student belongs to Class.

My test: a student should know what class it belongs to.

My student_spec:
it "should know what class it belongs to"
@student = Student.new
@class = Class.new(:name => "Math")
@class.students << @student
@student.class.name.should == "Math"
end
Failed! Apparently, you cannot insert into the array "<<". You need to do it like this:
@student.class = @class
Well, I'm not that stupid that it'd take me 3 hours to figure that out! My test was longer of course! I just made it simple for example's sake. :P




3 comments:

Ramon said...

I was told that with all the complex data I'm handling, it's best to use fixtures!

I don't know if this'll work directly with rSpec, but take a look at http://manuals.rubyonrails.com/read/chapter/26

Unknown said...

Wasn't your test failing because Class means class of ruby classes (like, ActiveRecord, or Student in your case), and @student.class should return Student?

Ramon said...

Hm.. I didn't know you had commented! Sorry about that. Maybe Class is a reserved word, yes. But I mean like a school class.