2011-11-02 56 views
0

嗨,我在我的EnrolledAccount模型中有以下方法,我想写rpec。我的问题是如何在rspec中创建Item和EnrolledAccount之间的关联。如何在rails中为模型方法编写rspec?

def delete_account 
    items = self.items 
    item_array = items.blank? ? [] : items.collect {|i| i.id } 
    ItemShippingDetail.destroy_all(["item_id in (?)", item_array]) unless item_array.blank? 
    ItemPaymentDetail.destroy_all(["item_id in (?)", item_array]) unless item_array.blank? 
    Item.delete_all(["enrolled_account_id = ?", self.id]) 
    self.delete 
    end 

回答

1

通常你会用factory_girl来创建一组数据库中的相关对象,针对你可以测试的。

但是,从您的代码中,我得到的关系是您的关系设置不正确。如果您设置了关系,则可以指示导轨在自动删除项目时执行什么操作。

E.g.

class EnrolledAccount 
    has_many :items, :dependent => :destroy 
    has_many :item_shipping_details, :through => :items 
    has_many :item_payment_details, :through => :items 
end 

class Item 
    has_many :item_shipping_details, :dependent => :destroy 
    has_many :item_payment_details, :dependent => :destroy 
end 

如果您的模型是这样定义的,删除将自动处理。

所以不是你delete_account你可以只写类似:

account = EnrolledAccount.find(params[:id]) 
account.destroy 

[编辑]使用像shoulda或显着的宝石,写规范是那么也很容易:

describe EnrolledAccount do 
    it { should have_many :items } 
    it { should have_many :item_shipping_details } 
end 

希望这可以帮助。

+0

感谢您的帮助。另外我想为这个模型写rpec。你能帮忙吗? – Salil

+0

新增应用程序示例(或显着)规范的关系。 – nathanvda

+0

我想知道我是否可以为delete_account方法编写rspec。 – Salil

相关问题