如何在rails中为模型方法编写rspec?
您好,我在我的 EnrolledAccount 模型中有以下方法,我想为其编写 rpec。我的问题是如何在 rspec 中创建 Item 和 EnrolledAccount 之间的关联。
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常,您会使用 factory_girl 在数据库中创建一组相关对象,您可以对其进行测试。
但是,从您的代码中我得到的印象是您的关系设置不正确。如果您设置了关系,则可以指示 Rails 在自动删除项目时执行哪些操作。
例如,
如果您的模型是这样定义的,删除将被自动处理。
因此,您可以编写如下内容,而不是
delete_account
:[编辑] 使用像 shoulda 这样的 gem 或者值得注意的是,编写规范也非常容易:
希望这会有所帮助。
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.
E.g.
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:[EDIT] Using a gem like shoulda or remarkable, writing the spec is then also very easy:
Hope this helps.