Rails 测试 - has_many 关联的固定装置

anc*_*jic 5 testing fixtures ruby-on-rails-4

我是单元测试的新手,并且有一个简单的用例。

有 2 种模型:CityResident。一个城市有很多居民。

我创建了 2 个固定装置 yml 文件:cities.yml、residents.yml。

居民.yml

resident1:
  name: resident1

resident2:
  name: resident2

resident3:
  name: resident3
Run Code Online (Sandbox Code Playgroud)

城市.yml

city1:
  name: city1
  residents: resident1, resident2, resident3
Run Code Online (Sandbox Code Playgroud)

当我运行一个应该总是通过的简单测试时,我收到一个错误

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)
Run Code Online (Sandbox Code Playgroud)

期望的是拥有一个带有 property 的 City 模型实例name: 'city1',以及一个residents包含 3 个 Resident 模型实例的数组的 property 。

在 City.rb 中,我指定了与 Resident 模型的 has_many 关系。在 Resident.rb 中,我指定了 own_to 与 City 模型的关系。

这应该是一件简单的事情,不是吗?

更新#1:

看来只能通过为驻地装置设置城市属性来做到这一点。

居民.yml

resident1:
  name: resident1
  city: city1 # added

resident2:
  name: resident2
  city: city1 # added

resident3:
  name: resident3
  city: city1 # added
Run Code Online (Sandbox Code Playgroud)

城市.yml

city1:
  name: city1
  # residents: resident1, resident2, resident3
Run Code Online (Sandbox Code Playgroud)

我想这已经足够了。

mah*_*off 1

我认为更新#1 很好。毕竟,这就是关联在数据库中实际存储的方式,而固定装置只是为数据库提供种子的一种方式。

如果你真的想要的话,你可以使用 FactoryGirl 或你自己的代码来干燥它,但测试应该是潮湿的而不是干燥的,并且延伸到固定装置。