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.

How to do End-to-end Testing with testRigor

Let us take the example of an e-commerce website that sells plants and other gardening needs. We will create end-to-end test cases in testRigor using plain English test steps.

Step 1: Log in to your testRigor app with your credentials.

Step 2: Set up the test suite for the website testing by providing the information below:

  • Test Suite Name: Provide a relevant and self-explanatory name.
  • Type of testing: Select from the following options: Desktop Web Testing, Mobile Web Testing, Native and Hybrid Mobile, based on your test requirements.
  • URL to run test on: Provide the application URL that you want to test.
  • Testing credentials for your web/mobile app to test functionality which requires user to login: You can provide the app’s user login credentials here and need not write them separately in the test steps then. The login functionality will be taken care of automatically using the keyword login.
  • OS and Browser: Choose the OS Browser combination on which you want to run the test cases.
  • Number of test cases to generate using AI: If you wish, you can choose to generate test cases based on the App Description text, which works on generative AI.

Step 3: Click Create Test Suite.

On the next screen, you can let AI generate the test case based on the App Description you provided during the Test Suite creation. However, for now, select do not generate any test, since we will write the test steps ourselves.

Step 4: To create a new custom test case yourself, click Add Custom Test Case.

Step 5: Provide the test case Description and start adding the test steps.

For the application under test, i.e., e-commerce website, we will perform below test steps:

  • Search for a product
  • Add it to the cart
  • Verify that the product is present in the cart

Test Case: Search and Add to Cart

Step 1: We will add test steps on the test case editor screen one by one.

testRigor automatically navigates to the website URL you provided during the Test Suite creation. There is no need to use any separate function for it. Here is the website homepage, which we intend to test.

First, we want to search for a product in the search box. Unlike traditional testing tools, you can identify the UI element using the text you see on the screen. You need not use any CSS/XPath identifiers.

For this search box, we see the text “What are you looking for?” So, to activate the search box, we will use the exact text in the first test step using plain English:
click "What are you looking for?"

Step 2: Once the cursor is in the search box, we will type the product name (lily), and press enter to start the search.

type "lily"
enter enter

Search lists all products with the “lily” keyword on the webpage.

Step 3: The lily plant we are searching for needs the screen to be scrolled; for that testRigor provides a command. Scroll down until the product is present on the screen:

scroll down until page contains "Zephyranthes Lily, Rain Lily (Red)"

When the product is found on the screen, testRigor stops scrolling.

Step 4: Click on the product name to view the details:

click "Zephyranthes Lily, Rain Lily (Red)"

After the click, the product details are displayed on the screen as below, with the default Quantity as 1.

Step 5: Lets say, we want to change the Quantity to 3, so here we use the testRigor command to select from a list.

select "3" from "Quantity"
After choosing the correct Quantity, add the product to the cart.
click "Add to cart"

The product is successfully added to the cart, and the “Added to your cart:” message is displayed on webpage.

Step 6: To assert that the message is successfully displayed, use a simple assertion command as below:

check that page contains "Added to your cart:"

Step 7: After this check, we will view the contents of the cart by clicking View cart as below:

click "View cart"

Step 8: Now we will again check that the product is present in the cart, under heading “Your cart” using the below assertion. With testRigor, it is really easy to specify the location of an element on the screen.

check that page contains "Zephyranthes Lily, Rain Lily (Red)" under "Your cart"

Complete Test Case

Here is how the complete test case will look in the testRigor app. The test steps are simple in plain English, enabling everyone in your team to write and execute them.

Click Add and Run.

Execution Results

Once the test is executed, you can view the execution details, such as execution status, time spent in execution, screenshots, error messages, logs, video recordings of the test execution, etc. In case of any failure, there are logs and error text that are available easily in a few clicks.

You can also download the complete execution with steps and screenshots in PDF or Word format through the View Execution option.

testRigor’s Capabilities

Apart from the simplistic test case design and execution, there are some advanced features that help you test your application using simple English commands.

  • Reusable Rules (Subroutines): You can easily create functions for the test steps that you use repeatedly. You can use the Reusable Rules to create such functions and call them in test cases by simply writing their names. See the example of Reusable Rules.
  • Global Variables and Data Sets: You can import data from external files or create your own global variables and data sets in testRigor to use them in data-driven testing.
  • 2FA, QR Code, and Captcha Resolution: testRigor easily manages the 2FA, QR Code, and Captcha resolution through its simple English commands.
  • Email, Phone Call, and SMS Testing: Use simple English commands to test the email, phone calls, and SMS. These commands are useful for validating 2FA scenarios, with OTPs and authentication codes being sent to email, phone calls, or via phone text.
  • File Upload/ Download Testing: Execute the test steps involving file download or file upload without the requirement of any third-party software. You can also validate the contents of the files using testRigor’s simple English commands.
  • Database Testing: Execute database queries and validate the results fetched.

testRigor enables you to test web, mobile (hybrid, native), API, and desktop apps with minimum effort and maintenance.

Additional Resources

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.

Join the next wave of functional testing now.
A testRigor specialist will walk you through our platform with a custom demo.