我为我的ror应用程序使用datamapper和postgres,在我的模型中我有这样的关联:
#/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 :(得分:1)
@buyer.transfers_out
是一个数组,@transfer
是一个对象。如果您想使用一个元素制作数组,则应使用@buyer.transfers_out = [ @transfer ]
或类似@buyer.transfers_out << @transfer
的内容。