You are here: Forums Ask a Rails expert How to write rspec for model a...
Posted in Forums : Ask a Rails expert
Authority 12
Posting Rating 0
Sign in to rate this post
|
Hi, im new to rspec. I googled about rpsec for model associations and got few information about it. But im not clear. I would be thankful if anyone can explain me with an example. Thanks. |
Authority 62
Posting Rating 100
Sign in to rate this post
|
Do you have an actual problem or are you looking for a tutorial? |
Authority 37
Posting Rating 94
Sign in to rate this post
|
Well, I’d say that most of the time you’re not going to want to test the associations themselves other than something rather superficial. ActiveRecord is very well tested and doing any sort of extensive testing on a relationship’s mechanics would probably be unnecessary. That being said, if you wanted to test that a particular association exists and is working, let’s assume we have two classes, Tree and Fruit. class Tree has_many :fruits end and class Fruit beongs_to :tree end If you wanted to test that a Tree does indeed have many fruits,
it "should have fruit" do
tree = Tree.create("....")
tree.fruits << Fruit.new(:type => "Apple")
tree.fruits << Fruit.new(:type => "Apple", :hasworms => true)
tree.should have(2).fruits
end
etc… |
Authority 50
Posting Rating 21
Sign in to rate this post
|
If you want to test that the actual model associations are defined, then this is useful: |
Authority 62
Posting Rating 0
Sign in to rate this post
|
Something I’ve been using to test the presence of an association (remember, we’re writing the tests first) is:
This of course is just a basic test to make sure that you have defined the association in the model. |
Authority 62
Posting Rating 100
Sign in to rate this post
|
I usually only check that the object responds to a given message because I normally don’t care if it’s from an association or a “manually” added method: # in the post model it "should have comments" do @post.should respond_to(:comments) end |
Ask a Rails expert : Use Rails to develop sites for both Designer and Programmer
Ask a Rails expert : Rails+RS232
Ask a Rails expert : Is this a good way to add Admin section
Ask a Rails expert : RSS feed maker in rails 2.1
Ask a Rails expert : Syncing with ugly legacy databases
Ask a Rails expert : juggernaut Error
Ask a Rails expert : gem "chronic" error
Ask a Rails expert : gem install error
Ask a Rails expert : need your help or views for distributed programming with ruby
Ask a Rails expert : how to refresh ruby files without restart production server