Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does findOrCreateBy work with other domain instances?

I'm trying to use findOrCreateBy to search for an object or instantiate one if I can't find one that matches, but it isn't working as I expected.

This is what I have:

String myBaz = "some unique string"
FooType myFooType = FooType.findByName("Large")

// The Foo table is empty, so this should give me a new Foo
Foo myFoo = Foo.findOrCreateByBazAndFooType(myBaz, myFooType)

assert myFoo.baz == myBaz 
assert myFoo.fooType == myFooType // Fails because myFoo.fooType is null, 
// but should be set to myFooType

What am I doing wrong? Why is the fooType not being properly set? Is this expected behavior or is this a bug in Grails?

like image 233
cdeszaq Avatar asked Nov 13 '22 02:11

cdeszaq


1 Answers

I'm not sure but it looks like you are trying to do this as a test. (based on your assert)

Dynamic methods added by Grails framework are not available in unit tests unless you mock the domain class. Now this is old grails code taken from another Question site but it may help

import grails.test.GrailsUnitTestCase   

class MessageControllerTests extends GrailsUnitTestCase {   

    def savedMessages   

    void setUp() {   
        super.setUp()   
        savedMessages = []   
        mockDomain(Message, savedMessages) //mocking the domain class   
        mockController(MessageController) //mocking the controller   
    }   

    void testMessageCanBeCreated() {   
        def messageController = new MessageController()   
        messageController.params.title = 'detail'  
        messageController.params.detail = 'some detail'  

        messageController.save() // executing the save action on the MessageController   

        assertEquals('list', messageController.redirectArgs.action)   
        assertEquals(1, savedMessages.size()) //assert the message has been saved   
    }   
}  
like image 77
PJT Avatar answered Feb 15 '23 23:02

PJT