Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

Struggling with an association test

Testing • Asked by John Sanderbeck

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.

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,242+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.