When starting with your first programming language, your thoughts about automatically testing your code with programmatic tests might be almost zero. At Fintory, we are a huge fan of testing your code programmatically. And NO, we don't do TDD (Test-driven Development), because of specific reasons – we are writing the tests after we tested the code manually and verifying that everything is working.
However, in each case (TDD or DTT – Development Then Tests) we are in the need of a huge test suite that works pretty solid to ensure that the test does also not fail when we are going to change any part of the codebase.
This premise often results in test suits being too much overwhelming and including a lot of duplicated code, which makes the test suite a bad pig to look at.
For example, have a look at the following code snippet:
This code snippet is a pain in our eyes, which our devs needed to refactor (what, refactor tests?!) some time ago.
Simplification made easy
With RSpec we have a nice block-scope variable called
subject. It can be used to define a "subject" which can then be called with its own name in the RSpec examples.
Let's see how we are able to simplify the above tests with the usage of
As you can see, using the nifty
subject helper can be very nice to clean up the tests. However, we can go a little further, since there is a nice side-effect in the scoping of the blocks in RSpec/Ruby.
Going a little further
Since we are using blocks in plain Ruby and due to the nature of RSpec that every example is a simple block, we are able to make use of this.
What have we done?
- We moved the
subjectto the top-level of the tests.
- We created a new
describeblock for paid content.
We mentioned the blocks before, and since we are not defining the
let once, but per example, we are now able to use the
subject for each example, but without redefining it in each
describe block since it is scoped and will work with the defined
let from the respective
We are using a different training instance for the "is paid" block than the "is free" block, but the
subject is still working as before. For all examples. BOOM!
Surely, we need to check where to put the subject, and what to expect from it. We also had cases, where every example was different from the other. In those cases, extensive usage of
subject does not make sense at all. However, we always have some cases, where the usage of it makes absolute sense in our eyes, and to have a clean test suite is always good.
If you don't want to mess around with the tests, you can ask us to write the tests for you or even build the complete product for you. We are always happy to help.