Mix testing fails on foreign keys

When I run “mix test”, there are about 200 tests which were automatically generated by Phoenix. However, none of them pass, because when the test tries to insert a new entry into the DB - such as a new post with author_id 1, it fails because there is no author with the id 1 within the users table (and the posts migration uses “add :author, references(:users)” to create a foreign key).

It seems like the tests are outdated, and do not contain the appropriate logic to ensure that a test user is created BEFORE the test post, and that the test post uses that test user’s id for the “author” field. Is there a way to re-create these tests automatically, which will ensure foreign key references are properly handled? If not, what is the best way to handle this?

The generated tests are intended to give you a place to start, but keeping them up-to-date as you add constraints is up to you. The @valid_attributes plumbing will likely need to be completely replaced, as once you’ve got foreign-key constraints it’s not possible to hard-code IDs like that.

You’ll run into similar issues with the generated controller tests - they are a good place to start, but mostly shatter once you add authentication / authorization to the app.

1 Like