Search code examples
grailsgroovycucumbergeb

Using I18N messages in grails cucumber test


I'm writting cucumber test cases in grails project. I want to access messages that are configured in message.properties file

e.g. I have a property configured in message.properties file as:

view.user.page.title = View user

I have a cucumber step ViewUserSteps.groovy

Given(~'^I looged in into the app$') { ->
  //code related to login
}
When(~'^I click view users tab"$') { ->
   // click user tab logic
}
Then(~'^I see I am on View User page$') { ->
   at ViewUserPage
}

And ViewUserPage.groovy is

import geb.Page
import grails.util.Holders
class ViewUserPage extends Page{
    static url = "${Holders.config.app.url}/users/view"
    static at = {
       waitFor(30,2) { 
           title == "Edit user"  // this title should be fetched from message.properties file 
       }
    }
}

Here in ViewUserPage I should be able to fetch the title that is configured in message.properties. Something like g.message(code:'view.user.page.title') or by some other way so that if I change in message.properties, no need to change test case. Any thoughts?


Solution

  • You can get ask the messageSource bean what the text is and then compare that to the result of the request.

    This can look like this (with responseData.errors.username being the result of the request (i.e. the When step):

    Then(~'^an error message is shown that the user name is already used$') {->
        assert responseData.errors.username.contains (message ('user.username.unique'))
    }
    

    message is a small helper function to get the text of the message:

    String message (String code) {
        getBean ('messageSource').getMessage (code, null, null)
    }
    

    We added message to the World object, so that it is automatically available in steps.