2013-02-15 61 views
0

在rspec控制器規範中,當您的模型has_one關聯時,定義valid_attributes方法的正確方法是什麼?rspec控制器測試中嵌套關聯的正確格式是什麼?

* Rails的3.2.12,rspec的2.12,factory_girl_rails 4.2.1 *

,如果你創建了有兩個模型,人腦,像這樣一個新的Rails項目:

rails new crowd 
cd crowd 
rails g scaffold person name:string 
rails g scaffold brain weight_kg:float 

(並所有的跑腿給他們關聯),你可以用這些模型結束:

class Brain < ActiveRecord::Base 
    belongs_to :person 
    attr_accessible :weight_kg 
    attr_accessible :person 
    attr_accessible :person_attributes 
    accepts_nested_attributes_for :person 
end 
class Person < ActiveRecord::Base 
    has_one :brain 
    attr_accessible :name 
    attr_accessible :brain 
    attr_accessible :brain_attributes 

    accepts_nested_attributes_for :brain 
    validates :brain, :presence => { :message => "Please give me a brain" } 
end 

相關自動生成的投機/控制器/ people_controller_spec.rb的內容:

describe PeopleController do 
    def valid_attributes 
    { 
     "name" => "A Person", 
    } 
    end 

此時valid_attributes是一個人無效的,因爲它缺少一個大腦。好的,我們來添加一個。但是如何?

錯誤:

def valid_attributes 
    { 
     "name" => "A Person", 
     "brain" => { "weight_kg" => "25" } 
    } 
    end 

^生成ActiveRecord::AssociationTypeMismatch: Brain(#86698290) expected, got ActiveSupport::HashWithIndifferentAccess(#84831840)

錯誤:

def valid_attributes 
    { 
     "name" => "A Person", 
     "brain" => Brain.new(:weight_kg => 25) 
    } 
    end 

^因爲它不會保存。錯誤將是Expected response to be a <:redirect>, but was <200>expected persisted? to return true, got false和另外2個。

錯誤:(假設有效的投機/工廠/ brain.rb)

def valid_attributes 
    { 
     "name" => "A Person", 
     "brain" => FactoryGirl.build(:brain), 
    } 
    end 

^這是錯誤的,因爲這也將不保存在創建/更新一個person記錄。錯誤將是Expected response to be a <:redirect>, but was <200>expected persisted? to return true, got false和另外2個。

回答

1
def valid_attributes 
    { 
     "name" => "A Person", 
     "brain_attributes" => { "weight_kg" => "25" } 
    } 

或者

def valid_attributes 
    { 
     "name" => "A Person", 
     "brain_attributes" => FactoryGirl.attributes_for(:brain) 
    } 
相關問題