Rails 测试 - has_many 关联的夹具 [英] Rails testing - Fixtures for has_many associations
问题描述
我是单元测试的新手,有一个简单的用例.
I am new to unit testing and have a simple use case.
有两种模型:城市、居民.一个城市有_许多居民.
There are 2 models: City, Resident. A City has_many Residents.
我创建了 2 个夹具 yml 文件:cities.yml、residents.yml.
I created 2 fixture yml files: cities.yml, residents.yml.
residents.yml
resident1:
name: resident1
resident2:
name: resident2
resident3:
name: resident3
cities.yml
city1:
name: city1
residents: resident1, resident2, resident3
当我运行一个应该总是通过的微不足道的测试时,我收到一个错误:
When I run a trivial test that should always pass, I get an error:
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'
的City模型实例,以及一个属性residents
的数组3 常驻模型实例.
What I expected is to have a City model instance with a property name: 'city1'
, and a property residents
an array of 3 Resident model instances.
在 City.rb 中,我指定了与 Resident 模型的 has_many 关系.在Resident.rb 中,我指定了与城市模型的belongs_to 关系.
Inside the City.rb, I specified has_many relation to the Resident model. And inside Resident.rb I specified belongs_to relation to the City model.
这应该是一件很简单的事情,不是吗?
This should be a simple thing to do, shouldn't it?
更新 #1:
似乎只能通过为 Resident 装置设置城市属性来实现.
It seems it is only possible to do it by setting the city property for the Resident fixtures.
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
我想这就足够了.
推荐答案
我认为 UPDATE #1 很好.毕竟,这就是关联实际存储在 DB 中的方式,而fixtures 只是为DB 播种的一种方式.
I think UPDATE #1 is fine. It's how the the associations are actually stored in the DB after all, and fixtures is simply a way to seed the DB.
如果你真的想要,你可以使用 FactoryGirl 或你自己的代码来干燥它,但测试应该是 DAMP not DRY 并且延伸到装置.
You could use FactoryGirl or your own code to DRY it up if you really want, but tests are supposed to be DAMP not DRY and that extends to fixtures.
这篇关于Rails 测试 - has_many 关联的夹具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!