开发者

Declare :child_key for has_many associations in factory_girl (datamapper)

I use datamapper and postgres for my ror application, in my models i have such associations:

#/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

Now i need to test in rspec by using factory girl. So, I've wrote this:

#/factories/account.rb
Factory.define :account do |f|
  f.transfers_out {|transfer| [transfer.association(:transfer)]}
  f.trans开发者_运维技巧fers_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 

and little transfer factory

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

So, I've tried to test creation of transfer from account:

    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

But that results me with failed test:

 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, what should i do and how should i declare the association with the child key in this situation? Would be thankful for any help.


@buyer.transfers_out is an array and @transfer is a single object. If you want to make an array with one element you should use @buyer.transfers_out = [ @transfer ] or something like @buyer.transfers_out << @transfer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜