Access Attribute of Rails Test Fixture in Associated FixtureSet
17:56 10 Feb 2016

Background

My application defines a one-to-many relationship between Employee and Company models. I've assigned the Employee fixture a company using the label of the Company fixture (37_signals). However, I also need to assign the company_uuid, which is generated by SecureRandom.uuid.


Example

app/models/

employee.rb

class Employee
  belongs_to :company
end

company.rb

class Company
  has_many :employees
end

test/fixtures/

employees.yml

employee:
  name: dhh
  company: 37_signals 
  company_uuid: <%= "Access the 37_signals company fixture's uuid here!" %>

companies.yml

37_signals:
  name: $LABEL
  company_uuid: <%= SecureRandom.uuid %>

Question

How can I access the attribute of a Fixture in another FixtureSet?


Attempted

I've attempted to use the following lines as solutions:

company_uuid: <%= ActiveRecord::FixtureSet.identify(:37_signals).company_uuid %>

The above finds the company's primary key id value, then calls the company_uuid method, which is undefined for the integer. This is invalid.

company_uuid: <%= companies(:37_signals).company_uuid %>

The above finds reports undefined method 'companies' for main:Object

Is there a conventional way to solve this problem?

ruby-on-rails ruby-on-rails-4 yaml fixtures