I am having problems with writing a test in rspec for will_paginate. The problem is that I have a model with an Owner that can have many pets. This leads to a factories.rb file that looks like this:
Factory.define :owner do |owner|
owner.personid "1111111"
owner.firstname "Nisse"
owner.lastname "Gunnarsson"
owner.street "Street"
owner.postaladress "38830"
owner.town "Town"
owner.phone "555-5555"
owner.mobile "555-5556"
owner.email "nisse@test.com"
owner.reminder true
end
Factory.define :pet do |pet|
pet.name "Hedvig"
pet.spec开发者_StackOverflow社区ie "Rabbot"
pet.breed "Lowen/vadur"
pet.colour "Madagaskar"
pet.association :owner
end
In my test I have
describe "Get show" do
before(:each) do
@owner = Factory(:owner)
30.times do
#@owner.pets << Factory.build(:pet)
@pet = Factory.build(:pet, :owner => @owner)
#@owner.pets << @pet
end
end
it "should have an element for each pet" do
get :show, :id => @owner
@owner.pets[0..2].each do |pet|
response.should have_selector("td", :content => pet.name)
end
response.should have_selector("td", :content => "Hedvig")
end
it "should paginate pets" do
get :show, :id => @owner
response.should have_selector("div.pagination")
response.should have_selector("span.disabled", :content => "Previous")
response.should have_selector("a", :href => "/pets?page=2",
:content => "2")
response.should have_selector("a", :href => "/pets?page=2",
:content => "Next")
end
end
So I create an Owner with the factory, no problem there. I can get the owners name by puts @owner.firstname
I can also create a pet, that has the correct owner (@pet.owner.firstname
), but I can not figure out how to fill the owners array (@owner.pets) with pets.
If I do a @owner.pets.count it is 0.
The applications works fine, I just can't figure out how to write the test. I am really new to both rails and TDD but I want to do it right.
Let me know if I should add more information.
Cheers Carl
Well first, doing @pet = Factory.build(:pet, :owner => @owner)
only builds a Pet object, but never saves it to the DB. You would want to use Factory.create(:pet, ...
to get it to actually save.
The @owner.pets
array is [] when you initially create the Owner object. If you simply create records in the DB with Factory.create
then yes, technically @owner
has pets, but the @owner
object doesn't know about them because it's already in memory with a .pets
array of [].
Instead, try this:
@owner.pets << Factory.create(:pet, :owner => @owner)
That will not only save it to the database, thus making any new calls to the database valid (such as now if you did Pet.count
you'd get back 1) but also the @owner.pets
array in memory will have a valid Pet object within it.
精彩评论