Search code examples
grailsgrails-2.0grails-test

Get config of other environment in Grails 2.*


I'm running Grails 2.1.1, and i'm looking for a way to get the value of variable set in production while i'm running on test environment. The config file :

development {
  config.url = "http://local"
}
test {
  config.url = "http://test.lan"
}
production {
  config.url = "http://prod.lan"
}

The only way i know to get config variables is grailsApplication.config.url


Solution

  • The standard config setup only looks at the current environment. Holders has the same current config as grailsApplication. You have to slurp the config again. Try using ConfigurationHelper. A spock test is below. (Note the sometimes doubled config.config is because the first config is the property (or short name for getConfig() method) and your key contains the second config.)

    import grails.test.mixin.TestMixin
    import grails.test.mixin.support.GrailsUnitTestMixin
    import spock.lang.Specification
    
    import org.codehaus.groovy.grails.commons.cfg.ConfigurationHelper
    
    @TestMixin(GrailsUnitTestMixin)
    class ConfigSpec extends Specification {
    
        void "test prod config"() {
            def configSlurper = ConfigurationHelper.getConfigSlurper('production',null)
            def configObject = configSlurper.parse(grailsApplication.classLoader.loadClass(grailsApplication.CONFIG_CLASS))
    
            expect:
            configObject.config.url == "http://prod.lan"
        }
    
        void "test dev config"() {
            def configSlurper = ConfigurationHelper.getConfigSlurper('development',null)
            def configObject = configSlurper.parse(grailsApplication.classLoader.loadClass(grailsApplication.CONFIG_CLASS))
    
            expect:
            configObject.config.url == "http://local"
        }
    
        void "test grailsApplication config"() {
            expect:
            grailsApplication.config.config.url == "http://test.lan"
        }
    
        void "test Holders config"() {
            expect:
            grails.util.Holders.config.config.url == "http://test.lan"
        }
    
    }