2011-07-04 20 views
0

我使用的DataMapper和我的RoR應用程序的Postgres,在我的模型,我有這樣的聯想:宣告:在factory_girl child_key的has_many關聯(DataMapper的)

#/models/account.rb 
has n, :transfers_out, "Transfer", :child_key => [ :account_from_id ] 
has n, :transfers_in, "Transfer", :child_key => [ :account_to_id ] 

#/models/transfer.rb 
belongs_to :account_from, "Account", :child_key => [:account_from_id], :required => true 
belongs_to :account_to, "Account", :child_key => [:account_to_id], :required => false 

現在我需要通過工廠女孩在rspec的測試。所以,我寫了這個:

#/factories/account.rb 
Factory.define :account do |f| 
    f.transfers_out {|transfer| [transfer.association(:transfer)]} 
    f.transfers_in {|transfer| [transfer.association(:transfer)]} 
    f.amount "0" 
end 

    Factory.define :account_big, :class => :account do |f| 
    f.name "MyMillionDollarPresent" 
    f.amount "10000" 
    end 

Factory.define :account_small, :class => :account do |f| 
    f.name "PoorHomo" 
    f.amount "100" 
end 

和小工廠轉移

Factory.define :transfer do |f| 
f.id "1" 
f.comment "payment" 
f.status "proposed" 
f.amount "0" 
end 

所以,我試圖從帳戶測試傳輸的創作:

describe Transfer do 

    before(:each) do 
    @account_big = Factory(:account_big) 
    @account_small = Factory(:account_small) 
    @transfer = Factory(:transfer) 
    end 

    it "should debit buyer" do 
    @buyer = @account_big 
    @buyer.transfers_out = @transfer 
    @transfer.amount = 3000 
    @buyer.amount -= @transfer.amount 
    @buyer.amount.should == 7000 
    end 

但是結果我與失敗的測試:

1) Transfer should debit buyer 
    Failure/Error: @buyer.transfers_out = @transfer 
    TypeError: 
     can't convert Transfer into Array 
    # ./spec/models/transfer_spec.rb:15:in `block (2 levels) in <top (required)>' 

Soo,我該怎麼做,我應該如何在這種情況下聲明與子鍵的關聯?感謝任何幫助。

+0

已嘗試f.transfers_out工廠(:轉讓)? – corroded

回答

1

@buyer.transfers_out是一個數組而@transfer是單個對象。如果你想用一個元素組成一個數組,你應該使用@buyer.transfers_out = [ @transfer ]或類似@buyer.transfers_out << @transfer

+0

但我應該怎麼做,如果我需要調用'@account = transfer.account_from',我應該如何確定工廠中的「belongs_to」關聯? – Maay

+1

如果您需要一組帳戶,您​​可以調用'@accounts = transfers.map {| t | t.account_from} .uniq'。正如我從您的模型中看到的,每次轉帳都可以有不同的帳戶。 – ujifgc