AndroC
AndroC

Reputation: 4884

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.

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.

Upvotes: 5

Views: 2635

Answers (1)

mahemoff
mahemoff

Reputation: 46509

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.

Upvotes: 1

Related Questions