2011-10-07 85 views
1

我在使用rspec爲will_paginate編寫測試時遇到了問題。問題是我有一個擁有許多寵物的所有者的模型。這導致factories.rb文件看起來像這樣:對於關聯對象的factory_girl和will_paginate的RSpec測試

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     "[email protected]" 
    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 

在我的測試我有

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

所以我創建所有者與工廠,沒有問題存在。我能得到業主的puts @owner.firstname

的名字,我也可以創建一個寵物,具有正確的所有者(@pet.owner.firstname),但我無法弄清楚如何填補業主陣列(@ owner.pets)寵物。

如果我做了@ owner.pets.count爲0。

的應用程序工作正常,我只是無法弄清楚如何編寫測試。我對軌道和TDD都非常陌生,但我想做的對。

讓我知道我是否應該添加更多信息。

乾杯卡爾

回答

1

那麼首先,做@pet = Factory.build(:pet, :owner => @owner)只有建立一個寵物的對象,但永遠不會保存到數據庫中。你會想用Factory.create(:pet, ...來實際保存。當您最初創建所有者對象時,@owner.pets數組爲[]。如果你簡單地在數據庫中創建記錄Factory.create然後是的,在技術上@owner有寵物,但@owner對象不知道他們,因爲它已經在內存中與.pets陣列的[]。

相反,試試這個:

@owner.pets << Factory.create(:pet, :owner => @owner) 

,不僅將它保存到數據庫中,從而使任何新的呼叫到數據庫中有效(比如現在,如果你沒有Pet.count那你將獲得1)但內存中的@owner.pets數組中也會有一個有效的Pet對象。

+0

太棒了!這解決了它。我想我還有很多東西需要學習。 (這很有趣)。太感謝了! – abegbg