2011-11-02 52 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

相關問題