Getting Started with Testing in Rails

Davit Khaburdzania
3 min readJan 7, 2016

--

One of the hardest things in testing world is to get started, because at first it seems so unworthy to write lots of more code. Also it could be new concept and you might be afraid of it, but trust me if you write you first tests, it gets easier and easier and in the end it will be worthy.

Here are few reasons why you should write tests:

  • It gives more confidence to change. You can change or refactor code without being afraid of breaking things.
  • Better code quality, because you have to think exact responsibilities for class and methods.
  • Whole story or intent of your class or method is visible and understandable just by looking at tests.

Tools I use

Rspec gives you clean Domain Specific Language for describing your tests.

Factory Girl is a replacement of fixtures and comes with tons of great features like sequences, traits and so on.

FFaker for generating fake data in Factory Girl.

Shoulda-matchers collection of matchers for RSpec to test different kind rails functionality.

Pry-byebug for debugging.It’s really handy, when you don’t know why test magically is not working

What kind of tests I write

Models

I test Models for validations and associations:

All these matchers have_many, validate_presence_of which come from Shoulda-matchers.

I also test methods and scopes for Model:

I use context to choose between different states of my function. Always start description of context using when and with, that way tests are far more clear and readable.

Services

Services are used a lot in my projects. I use them to refactor fat functions or extract external service operations. Testing services is like testing any other object or class. If you write correct service, which does only one thing, it will be very easy to test it.

Controllers

I only test if some methods are executed correctly, when writing Controller Tests, because its models or services responsibility to have tests for its implementation and we don’t want to write them twice. Of course you should test responses and redirects too.

In the last It you can see that I am using is_expected which is same as writing expect(response) , it always tests expectation on current context which in this case is response.

I also test Decorators and helpers but testing them are not any different then others.

It’s only brief overview of testing in rails and I hope it will inspire you to start writing them on your own.

If you liked what I wrote, Follow me on twitter 🙌

--

--