Rails testing - Fixtures for has_many associations

眉间皱痕 提交于 2021-02-08 18:30:51

问题


I am new to unit testing and have a simple use case.

There are 2 models: City, Resident. A City has_many Residents.

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)

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.

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?

UPDATE #1:

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

I guess it will have to suffice.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/24129045/rails-testing-fixtures-for-has-many-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!