New Discussion

Notifications

You’re not receiving notifications from this thread.

Struggling with an association test

1
Testing

I have a project that has a User, a Building, and a Role
There is a building_roles table that is user_id, building_id, and role_id
Then I have a has_many :users through building_roles
There is a validation on the user that verifies it must have at least one role in a building

Can't for the life of me get the association to work in a factory for testing

Anyone done this before?

Thought 1:

Sounds like you just need to make sure the role and building are created before the user is. Then, in your model, make sure that the user is associated with a default role and building using something like a before_validation.

Then, in your test suite, make sure you create that default role and building before running the test.

Thought 2:

By factory, I'm assuming you're using Factory Girl. You could try using a callback such as before(:create) to create the role and building before the factory is created. Then, use those for the associations.

Join the discussion
Create an account Log in

Learning Ruby on Rails? Join our newsletter.

We won't send you spam. Unsubscribe at any time.