2012-10-31 52 views
28

查看控制器測試教程,作者給出了一個rspec測試示例,用於測試控制器操作。我的問題是,他們爲什麼使用方法attributes_for而不是build?沒有明確的解釋,爲什麼attributes_for被使用,除了它返回值的散列。FactoryGirl和Rspec Testing中的attributes_for的含義

it "redirects to the home page upon save" do 
    post :create, contact: Factory.attributes_for(:contact) 
    response.should redirect_to root_url 
end 

教程鏈接在這裏找到:http://everydayrails.com/2012/04/07/testing-series-rspec-controllers.html的例子在開始題目部分Controller testing basics

回答

54

attributes_for被發現會返回一個哈希,而build就返回一個非持久化的對象。

鑑於以下工廠:

FactoryGirl.define do 
    factory :user do 
    name 'John Doe' 
    end 
end 

這裏是build結果:

FactoryGirl.build :user 
=> #<User id: nil, name: "John Doe", created_at: nil, updated_at: nil> 

attributes_for

FactoryGirl.attributes_for :user 
=> {:name=>"John Doe"} 

結果我發現attributes_for我的功能非常有幫助測試,因爲我可以做像以下這樣的事情o創建一個用戶:

post :create, user: FactoryGirl.attributes_for(:user) 

當使用build,我們將不得不從user實例手動創建的屬性的散列,並且將它傳遞給post方法,如:

u = FactoryGirl.build :user 
post :create, user: u.attributes # This is actually different as it includes all the attributes, in that case updated_at & created_at 

我通常使用build & create當我直接想要物體而不是屬性散列

讓我知道你是否需要更多細節

+0

謝謝pjam,我現在明白了!你正在變得越來越像一個rspec導師,因爲我在overstackflow中。 – jason328

+0

一直在尋找這個答案。儘管如此......如果在模型中無法訪問某些屬性,我將如何繞過'post:create,user:u.attributes'? –

+0

我不知道我明白你想要什麼,你是說如果某些屬性不在attr_accessible列表中?然後我不明白是什麼問題,我可能會在這裏丟失一些東西 – pjam

相關問題