【问题标题】:How can I test belongs_to, has_one, or has_many associations with test::unit?如何测试 belongs_to、has_one 或 has_many 与 test::unit 的关联?
【发布时间】:2013-10-10 16:12:39
【问题描述】:

我对 Rails 测试很陌生,我尝试使用 shoulda,但它破坏了我放入的任何模型,所以我想我应该手动测试它们。

所以我对你的问题哦,伟大的 SO 专家是这样的:

如何使用 test::unit 来测试一个模型是否与另一个模型相关联?

【问题讨论】:

  • 到目前为止你有什么?

标签: ruby-on-rails ruby unit-testing ruby-on-rails-4 testunit


【解决方案1】:

嗯,最明显的解决方案是这样的:

user = User.create(name: 'User')
2.times { user.friends.create(name: 'Other User') }

assert_equal(2, user.friends.count, "Unexpected associated records count")

但这基本上更像是测试rails本身,你不应该为此烦恼。

我会检查user.respond_to?(:friends)。但是,当然,如果有人用那个名字定义了一个方法,它就会失败

【讨论】:

  • 这似乎工作得很好。如果有人让方法名称成为朋友,我想我们会改变它。谢谢!
  • 第一种方法是测试“has_many”关联的唯一方法吗?
  • 我想通了。我可以检查它是否响应 :new
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多