2

Context: I've created a new plugin named AppDomain that includes the Mongo 3.0.1 plugin. It has one domain class (Person), and one integration test (PersonSpec).

Issue: The id is being generated. The appdomain database and person collection are being created in Mongo. However, the integration test is failing at the collection count.

Notes: Having consulted all documentation that I could find and having made the bare minimum of changes to the generated AppDomain plugin code, I'm at a loss as to why the persistence test included here is failing. I have a similar plugin configured with grails 2.2.2 using junit tests that works just fine.

Any help is appreciated.

package appdomain

class Person {
    String firstName
    String lastName
}

-

package appdomain

import grails.test.mixin.TestMixin
import grails.test.mixin.mongodb.*
import spock.lang.*

@TestMixin(MongoDbTestMixin)
class PersonSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    void "can persist a person to the appdomain mongo database"() {
        given: "a person"
        def aPerson = new Person(firstName: "Homer", lastName: "Simpson")

        when: "the person is saved"
        aPerson.save()

        then: "the person has an id"
        aPerson.id != null //Passes

        and: "the Person collection contains one item"
        Person.list().size() == 1 //Fails with Person.list().size() == 0
    }
}
Jason Stonebraker
  • 809
  • 1
  • 10
  • 11
  • Do you get the same result when you use findAll() or getAll() instead of list()? – Özgür Eroğlu Jul 13 '14 at 18:42
  • I do @ÖzgürEroğlu. findAll() and getAll() fail in the same way. As does Person.count(). – Jason Stonebraker Jul 13 '14 at 18:52
  • @JasonStonebraker, maybe you have some incorrect DB option in the config test environment? For example you DB is not created and `dbCreate = "validate"` or is absent. I think with mongo must exists similar prefrences. – wwarlock Jul 28 '14 at 10:45

1 Answers1

1

GORM doesn't always persist the object right after you call save.

Official Reference Says

The save method informs the persistence context that an instance should be saved or updated. The object will not be persisted immediately unless the flush argument is used.

Therefore you should call save to flush the session immediately so that the changes take effect right away.

. . .
when: "the person is saved"
        aPerson.save(flush:true)
. . .

Sometimes, save fails (even if flush:true is supplied) due to validation or other non-common errors! If you want to get an Exception in these situations you should also add failOnError:true like this

. . .
when: "the person is saved"
        aPerson.save(flush:true, failOnError:true)
. . .

Read more about save method in the Official Reference Page

Amanuel Nega
  • 1,899
  • 1
  • 24
  • 42