Importance of having one class per file

The practice of one class file is good as it helps aid the developer in knowing what file contains a given class from a list of files in a directory it also allows for a single context to be maintained. Another area that is helpful is with grouping like context code together in separate files.

The case I bring up is with Cucumber and the traditional substantial single steps definition file it tends to have. To navigate through this one file is tedious at best, and your IDEs can only help so much.

When everything is one file, there is no way to know if you have updated all step definitions with any changes for a given context making it difficult to maintain. With the ease, it is to add the next step definition to the bottom of the file continually adds to the context mixing and reducing of maintainability of the step definitions. If you do not put in place a pattern to help maintain the code, you may find yourself abandoning your automated tests and allow your code to rot.

Through my efforts of managing an ever-growing automated test library, I have come up with two solutions:

Approach #1 (Step Definition File Per Feature)

Here you create a step definition file with the same name as your feature file and place all non-shared step definitions here. When you start having your step definitions shared across feature files, you locate them to a shared step definition file.

Pro
– Easy to find step definitions for a given feature file

Con
– The more step definitions you share, the larger your shared step definition file gets and starts to suffer the maintenance issues of a substantial step definition file.
– For features that use all shared files, you do not have a step definition file created.

Approach #2 (Step Definition File Per Component)

Provided you are using a page object model pattern; this approach has you creating the step definition files from supporting classes. For example, you have a component for grids named grid.rb. You would then create a step definition file of grid_steps.rb and have all step definitions that use this control in it.

Pro
– Step definitions related to controls are all located in one location.
– Increase in maintenance: as you update the control you can make the update one place.

Con
– Step definitions for you feature files may not be easily found without understanding the gherkin.

I have moved towards the second approach for our automated UI tests, and it has helped improve maintainability of the large suites of tests. Try these approaches yourself to help increase the maintenance of your test suit and see which works best for you.