My mocha tests work separately, but fail when run all at once
Here's one thing that could be creating race conditions that will make you crazy. You aren't passing a callback when dropping the users collection. I can't say for sure if this will ever cause a problem such as the test user being inserted before the collection gets dropped, but this pattern of failing to use callbacks properly to wait for asynchronous operations to complete is a recipe for your program to misbehave in hard-to-debug ways. Try this:
before (done) -> # Drop all users from database User.collection.drop (err) -> # Create our test user, his username is John Egbert User.create password: 'test123' public: {username: 'john'}, done
2nd suggestion: put console.log
statements at the beginning (1st statement) of every describe/before/it
and another one immediately prior to calling done()
and see if they appear in exactly the order you expect.
I found that for some reason the public.username
index is removed when running the tests together with npm test
. But was maintained when running each test alone.
I changed the following in the test/models.coffee
:
# Create our test user, his username is John Egbert User.create password: 'test123' public: {username: 'john'}, done
To the following:
# Create our test user, his username is John Egbert User.create password: 'test123' public: {username: 'john'}, -> User.collection.ensureIndex { 'public.username': 1 }, { unique: true }, (err) -> throw err if err done()
...which calls ensureIndex an internal mongoose function which is called when the model is compiled initially, but is removed for some reason during the test's life-cycle.
Using Mongoose 3.5.4