我在rspec中为will_paginate编写测试时遇到问题。问题是我有一个拥有许多宠物的主人的模型。这会导致一个看起来像这样的factories.rb文件:
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.specie "Rabbot"
pet.breed "Lowen/vadur"
pet.colour "Madagaskar"
pet.association :owner
end
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.specie "Rabbot"
pet.breed "Lowen/vadur"
pet.colour "Madagaskar"
pet.association :owner
end
在我的测试中我有
end
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
所以我用工厂创建了一个所有者,没问题。我可以通过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
我也可以创建一个拥有正确所有者()的宠物,但我无法弄清楚如何用宠物填充所有者数组(@ owner.pets)。
如果我执行@ owner.pets.count,则为0。
应用程序工作正常,我只是无法弄清楚如何编写测试。我对rails和TDD都很陌生,但我想做得对。
如果我要添加更多信息,请告诉我。
干杯卡尔
答案 0 :(得分:1)
首先,执行@pet = Factory.build(:pet, :owner => @owner)
只会构建一个Pet对象,但永远不会将其保存到数据库中。您可能希望使用Factory.create(:pet, ...
来实际保存它。
最初创建Owner对象时,@owner.pets
数组为[]。如果您只是使用Factory.create
在数据库中创建记录,那么技术上@owner
有宠物,但@owner
对象不知道它们,因为它已经在内存中{{1数组[]。
相反,试试这个:
.pets
这不仅会将其保存到数据库中,因此对数据库的任何新调用都是有效的(例如现在,如果你{1}}你回来了1),还有@owner.pets << Factory.create(:pet, :owner => @owner)
数组在内存中将有一个有效的Pet对象。