0

任何人都通過這個?配置工廠嵌套表格

場面上創建用戶,其中嵌套形式:

  1. 用戶HAS_ONE簡介
  2. 檔案belongs_to的用戶

所以我廠以這種方式配置,但是當我運行測試總是給我帶來這個結果:

Failure/Error: user_attributes[:user_attributes][:profile_attributes] = Factory.attributes_for :profile 
    NoMethodError: 
     undefined method `[]=' for nil:NilClass 

Factory.define :user do |f| 
    f.after_build do |user| 
    f.email     '[email protected]' 
    f.password    'password' 
    f.password_confirmation 'password' 
    user.profile ||= Factory.build(:profile, :user => user) 
    end 
end 

Factory.define :profile do |f| 
    f.after_build do |profile| 
    profile.user ||= Factory.build(:user, :profile => profile) 

    f.nome   'alguem' 
    f.sobrenome  'alguem' 
    f.endereco  'rua x' 
    f.numero  '95' 
    f.genero  'm' 
    f.complemento 'casa' 
    f.bairro  'bairro x' 
    f.cidade  'cidade x' 
    f.estado  'estado x' 
    f.cep   '232323' 


end 

end 

Users_spec

describe "CreateUsers" do 

    before :each do 

     user_attributes = Factory.attributes_for :user 
     user_attributes[:user_attributes][:profile_attributes] = Factory.attributes_for :profile 

    @user = User.new(user_attributes) 

    end 
+1

在嘗試分配user_attributes [:user_attributes] [:profile_attributes]之前,您可以嘗試提出user_attributes.inspect嗎?你的錯誤告訴你,user_attributes [:user_attributes]是零,所以當你試圖用[:profile_attributes]對它進行索引時,你正在使用一個方法,[] =,一個零值。 – 2012-02-17 20:29:51

回答

1

假設你正在試圖自動當你創建一個用戶,然後嘗試建立這種方式,使用新FactoryGirl語法創建一個配置文件:

工廠文件:

FactoryGirl.define do 
    factory :user do 
    email     '[email protected]' 
    password    'password' 
    password_confirmation 'password' 
    after_build do |profile| 
     user.profile << FactoryGirl.build(:profile, :user => user) 
    end 
    end 

    factory :profile do 
    nome   'alguem' 
    sobrenome  'alguem' 
    endereco  'rua x' 
    numero  '95' 
    genero  'm' 
    complemento 'casa' 
    bairro  'bairro x' 
    cidade  'cidade x' 
    estado  'estado x' 
    cep   '232323' 
    user 
    end 
end 

請注意在配置文件工廠中添加了user,並在配置文件記錄中定義了關聯。如果您的用戶工廠名爲:user,則不必傳遞任何參數。

然後,您應該能夠調用

@user = FactoryGirl.build(:user) 

,它會建立兩個用戶和個人資料。您可以致電@user.profile查看簡介。

如果您致電@user = FactoryGirl.create(:user),它將創建用戶和配置文件,將user_id插入配置文件記錄。

+0

有趣!是的,這是真的,非常感謝你mottott。 – dcalixto 2012-02-18 17:47:36