Turn your manual testers into automation experts Request a DemoStart testRigor Free

Grails Testing

Grails Testing

Grails is an open-source, Java-based web application framework that uses the Apache Groovy programming language. It’s one of the most productive frameworks, providing a stand-alone development environment. Graeme Rocher released the first build in October 2005 under the initial name, Groovy on Rails, which was later changed to Grails. Grails follows the “coding by convention” paradigm, which means the framework reduces the number of decisions a developer needs to make, without necessarily sacrificing flexibility. It adheres to the Don’t Repeat Yourself (DRY) principles. Grails is a full-stack framework that addresses many limitations of other web development frameworks through its core technology and in-built plugins. Grails packs an object mapping library for different databases, View technology for rendering HTML and JSON files, a controller layer on Spring Boot, flexible profiles for AngularJS, React, and more, plus an interactive command line based on Gradle. Companies like LinkedIn, Biting Bit, and Transferwise use Grails in their technology stack.

How to test Grails applications

When it comes to testing, Grails provides many methods to simplify both unit testing and functional testing. Let's discuss the three main types of testing that can be performed in a Grails application and understand the best-suited testing tool or framework for each.

Unit Testing

Unit testing involves examining the smallest parts of an application - the units - by isolating them and checking their behavior. In a Grails application, units could be domain classes, controllers, services, and tag libraries, among other components. Grails supports unit testing out of the box using the Spock testing framework, a powerful yet user-friendly testing library in the Groovy ecosystem.

Here's a simple example of a unit test for a hypothetical BookService in a Grails application:
import grails.testing.gorm.DataTest
import spock.lang.Specification

class BookServiceSpec extends Specification implements DataTest {

  BookService bookService // the service we're testing

  void setup() {
    bookService = new BookService()
  }

  void "test find book by id"() {
    given: "a book instance"
    Book book = new Book(title: 'Unit Testing in Grails', author: 'John Doe').save()
    
    when: "find book by id"
    Book foundBook = bookService.findBookById(book.id)
    
    then: "the returned book should match the saved book"
    foundBook.id == book.id
    foundBook.title == book.title
    foundBook.author == book.author
  }
}

In this unit test, we're creating an instance of a book, saving it, and then using the findBookById method of the BookService class to find the book we just saved. We're then checking to see if the book returned by findBookById matches the book that we saved.

Notice the use of the given, when, and then blocks. This is part of Spock's highly readable BDD-style (Behavior Driven Development) syntax. given is where you set up the conditions for your test, when is where the action of the method you're testing takes place, and then is where you assert the expected outcome.

Integration Testing

Integration testing is an indispensable part of the software testing life cycle. It focuses on combining individual software modules and testing them as a group. This ensures the communication and interaction between these units function as expected, verifying the correctness, performance, and reliability of the integrated components.

In the Grails ecosystem, integration tests play a vital role in verifying the collaboration between controllers, services, domain classes, and even external systems such as databases, message queues, and more. Grails comes with built-in support for integration testing, employing the Spock testing framework for its easy-to-read BDD-style syntax.

Let's consider an example of an integration test for a hypothetical BookService that interacts with a Book domain class in a Grails application:
import grails.testing.services.ServiceUnitTest
import spock.lang.Specification

class BookServiceIntegrationSpec extends Specification implements ServiceUnitTest<BookService> {

  void "test save and find book"() {
    given: "a book instance"
    Book book = new Book(title: 'Integration Testing in Grails', author: 'John Doe')
    
    when: "book is saved using the service"
    bookService.saveBook(book)
    
    and: "find the saved book"
    Book foundBook = bookService.findBookById(book.id)
    
    then: "the found book should match the saved book"
    foundBook.id == book.id
    foundBook.title == book.title
    foundBook.author == book.author
  }
}

In this example, we are creating a Book instance and using the BookService to save it. We then find the saved book using the service's findBookById method. Finally, we verify that the saved book matches the one we created.

The key distinction between this integration test and a unit test is that the integration test will interact with the actual database, ensuring that our service's database operations are functioning correctly. Grails handles the creation and clean-up of the test environment, including database transactions, for each test execution. This ensures each test runs in isolation, providing accurate and reliable test results.

Integration testing is crucial for verifying the behavior of your application when its components interact, catching errors that might not appear during unit testing. As such, it is an invaluable tool in your Grails testing arsenal.

System or End-to-End Testing

E2E testing, also known as system testing, is a software testing method that validates the complete functional flow of an application, from start to end. The primary purpose of E2E testing is to simulate the real user scenario and validate the system under test and its components for integration and data integrity. It tests a complete application environment in a setup that mimics real-world use, such as interacting with a database, communicating with other network services, or interacting with other hardware, applications, or systems if appropriate.

For instance, in a typical e-commerce application, an E2E test might simulate a user logging in, searching for a product, adding it to the cart, checking out, and confirming the order. The test would involve all layers of the application from the user interface (UI) to the database, and might even include external services, such as payment gateways or email notifications.

Several tools might be used for Grails system testing:
  • Geb Framework
  • Selenium
  • testRigor

Geb Framework

Grails provides the create-functional-test command, which leverages the Geb framework. Geb is a browser automation solution that uses the Selenium webdriver for browser interactions, JQuery for content selection, and Groovy's Page Object model for organizing tests in a maintainable manner. To create a functional test, execute the command:
$ grails create-functional-test MyFunctional
This command creates a new file named MyFunctionalSpec.groovy in the src/integration-test/groovy directory. The test is annotated with Integration to indicate it's an integration test and will extend the GebSpec class. Here's a sample script:
package grails.geb.multiple.browsers

import geb.spock.GebSpec
import grails.testing.mixin.integration.Integration

@SuppressWarnings('JUnitPublicNonTestMethod')
@SuppressWarnings('MethodName')
@Integration
class DefaultHomePageSpec extends GebSpec {
  void 'verifies there is a _<h1>_ header with the text "Welcome to Grails" when we visit the home page.'() {
    when:
    go '/'
    
    then:
    $('h1').text() == 'Welcome to Grails'
  }
}

These test scripts can be run against Chrome, Firefox, and HTMLUnit (non-GUI) browsers. However, you'll need to download the browser-specific drivers and configure them in the config file to run on these browsers. Though Geb supports multiple browsers, its options are somewhat limited. For instance, it doesn't support Safari, Edge, Opera, and others. It also lacks features compared to other web automation tools, like parallel execution.

Selenium

Selenium is a longstanding, highly recognized tool for web automation. As an open-source tool, it supports scripting in various programming languages. Despite its popularity, many companies have transitioned to other tools due to Selenium's downsides. These include complex scripting, slow execution speed, extensive test maintenance effort, dependency on various third-party integrations, costly infrastructure, and a high rate of false-positive bugs. You can learn more about Selenium here and its disadvantages here.

testRigor

testRigor is an AI-powered, codeless automation tool specifically designed for end-to-end testing. It provides the simplest way to construct robust functional tests. The best part is that even manual testers on the team can efficiently use it.

testRigor is a versatile system that supports various types of testing:
  • Web and mobile browser testing
  • Native and hybrid mobile app testing
  • Native desktop testing
  • API testing
  • Visual testing

Being a codeless automation tool, testRigor makes interaction with the application under test quite straightforward. For instance, to click a Submit button, you simply write click "Submit". To input data, write enter "Sam" into "user name". For validation, you could use something like check the page contains "Hello, Google!". This design allows testRigor to help create test scripts in plain English without dependence on scripting languages.

There are numerous other features of testRigor, such as:
  • It facilitates effortless parallel execution of test scripts across multiple browsers and platforms.
  • testRigor's integrated AI-powered engine captures the element's relative position. This means any changes in the element locator won't break the test.
  • It provides 2FA login support, including login with email, text messages, and Google Authenticator.
  • Validation of texts in images used on webpages is possible using the OCR functionality.
  • testRigor offers built-in integrations with industry-leading CI platform tools, infrastructure providers, test management tools, and enterprise communication tools.

You can read more about testRigor's features here.

Let's review a sample test script:
click "Sign up"
generate unique email and enter it into "Email", then save it as "generatedEmail"
generate unique name and enter it into "Name", then save it as "generatedName"
enter "PasswordSecure" into "Password"
click "Submit"
check that email to stored value "generatedEmail" was delivered
click "Confirm email"
check that page contains "Email was confirmed"
check that page contains expression "Hello, ${generatedName}"

This script showcases the power and simplicity of testRigor in action. It provides the means for anyone on your team to create comprehensive, robust end-to-end tests without the need for complex coding.

Conclusion

Grails, as one of the most commonly used web development frameworks, demands comprehensive testing at every phase of the development cycle. Thorough testing is not just a good practice but a necessity for building reliable and high-performing applications.

Each stage of development requires its specific type of testing - unit testing at the component level, integration testing to ensure different components work together, and end-to-end or system testing for verifying the system as a whole.

In conclusion, implementing a comprehensive testing strategy using the aforementioned tools allows teams working with the Grails framework to not just deliver functional software but a high-quality product that meets user expectations and stands the test of time. The importance of testing cannot be overstated; it's an investment in the product's quality, user satisfaction, and ultimately, the success of the software application.