我是单元测试的新手,有一个简单的用例。
有 2 个模型:City,Resident。一个城市有_很多居民。
我创建了 2 个 fixture yml 文件:cities.yml、residents.yml。
residents.yml
resident1:
name: resident1
resident2:
name: resident2
resident3:
name: resident3
cities.yml
city1:
name: city1
residents: resident1, resident2, resident3
当我运行一个应该总是通过的简单测试时,我得到一个错误:
Minitest::UnexpectedError: ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'residents' in 'field list': INSERT INTO `cities` (`name`, `residents`, `created_at`, `updated_at`, `id`) VALUES ('city1', 'resident1, resident2, resident3', '2014-06-09 20:42:22', '2014-06-09 20:42:22', 574963714)
我期望的是拥有一个具有属性name: 'city1'
和属性residents
的城市模型实例3 常驻模型实例。
在 City.rb 中,我指定了与 Resident 模型的 has_many 关系。在 Resident.rb 中,我指定了与 City 模型的 belongs_to 关系。
这应该是一件简单的事情,不是吗?
更新 #1:
似乎只能通过为 Resident fixtures 设置 city 属性来实现。
residents.yml
resident1:
name: resident1
city: city1 # added
resident2:
name: resident2
city: city1 # added
resident3:
name: resident3
city: city1 # added
cities.yml
city1:
name: city1
# residents: resident1, resident2, resident3
我想这就足够了。
最佳答案
我认为更新#1 很好。毕竟这就是关联实际存储在数据库中的方式,固定装置只是一种为数据库播种的方式。
如果你真的想要,你可以使用 FactoryGirl 或你自己的代码来 DRY 它,但测试应该是 DAMP not DRY并且延伸到固定装置。
关于testing - Rails 测试 - has_many 关联的固定装置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24129045/