Hi i have the following method in a my EnrolledAccount models for which i want to write rpec. My question is how can i create the association between Item and EnrolledAccount in 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
Generally you would use factory_girl to create a set of related objects in the database, against which you can test.
But, from your code I get the impression that your relations are not set up correctly. If you set up your relations, you can instruct rails what to do when deleting an item automatically.
Eg
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
If your models are defined like that, the deletion will be automatically taken care of.
So instead of your delete_account
you can just write something like:
account = EnrolledAccount.find(params[:id])
account.destroy
[EDIT] Using a gem like shoulda or remarkable, writing the spec is then also very easy:
describe EnrolledAccount do
it { should have_many :items }
it { should have_many :item_shipping_details }
end
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.