Ask A Question

Notifications

You’re not receiving notifications from this thread.

Struggling with an association test

John Sanderbeck asked in 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?

Reply

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.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.