Search code examples
ruby-on-railsruby-on-rails-4testinghas-and-belongs-to-manyfixtures

How to set up fixtures for many-to-many through association (with values for the intermediary model)?


Organization and User have a many-to-many relationship through Relationship. I read here about setting up fixtures for a HABTM association:

#users.yml
one:
  organizations: one
  email: [email protected]
  ...

#organizations.yml
one:
  name: "Company A"
  ...

This should establish a relationship between the organization and user in the fixtures, and does not require relationships.yml thereby keeping the set-up nice and clean.

However, in my case I need to specify certain variables for the relationships. For example, in the relationship table a moderator boolean is set. How can I include such values in the fixtures? I know I could do this by using relationships.yml and create my relationships there (which is how I've currently implemented it). But not needing relationships.yml keeps it so much cleaner. Is there a way to set these variables for the relationships without relationships.yml? For example, something like:

#users.yml
one:
  organizations: one(moderator: true)
  email: [email protected]
  ...

Solution

  • Fixtures simply won't support the inline syntax you're referring to. Fixtures are very limited, and don't even support, e.g., doing inline definitions for objects related via has_many. So, aside from committing a patch to Rails, you only have two options that I'd suggest:

    1. Use relationships.yml, like you mentioned already. Or...

    2. Use factory_girl instead of fixtures. Factories come with their own set of problems, but not being flexible isn't one of them.