Building Groovy projects with Gradle makes perfect sense. IntelliJ IDEA is also far and away the best IDE for Groovy, Grails & Gradle development. So why does it have to be so difficult to get a working setup inside IntelliJ?

Fortunately there's an easier way...

TL;DR

Don't bother trying to get IntelliJ to import the project. Use the Gradle IDEA plugin by adding apply plugin: 'idea' to build.gradle and then run gradle idea. That creates the IntelliJ project so it will then open up correctly.

There are a couple of obvious ways to get a Gradle project into IntelliJ, but they don't yield the results you'd expect.

Note this applies to IntelliJ 13.1. Subsequent versions may have fixed this flaw.

Attempt 1: Import as a Gradle project

IntelliJ has a File -> Import Project menu item. This has the following effect:

  1. The Gradle files are identified and IntelliJ creates a Gradle-based project with a module for the gradle wrapper. Sometimes (just for giggles) it would replace build.gradle with an entirely new one for Java projects.
  2. The Groovy sources aren't picked up, and you need to create a new module for them. Even with that I couldn't get it to offer a 'Run' option for the classes.
  3. Gradle builds work, but you don't get code completion or individual test runs.

Attempt 2: Import as a Groovy project

Importing as a Groovy project and ignoring Gradle almost seems to work, except that the dependencies aren't loaded from Gradle. Even adding the Gradle facet afterwards didn't seem to link it with the Groovy project.

Attempt 2: Just "open" the Gradle project

This has a similar effect to attempt #1.

Solution: Let Gradle do the legwork

Gradle has a plugin to generate the IDEA project files, allowing you to just open the project normally in IntelliJ:

  1. Ensure the source directories are present
  2. Add the idea plugin to build.gradle
  3. Run the idea task: $ gradle idea

An example build.gradle including Groovy, Spock and IntelliJ support:

The result is an IntelliJ project with all the good bits, including:

  • Code completion, including dependencies from Gradle
  • Debugger support during Gradle tasks
  • Run and debug individual Spock tests (right-click the Specification and select Run/Debug)