Is it okey to DRY the action of a test?

104 Views Asked by At

From my understanding of AAA - arrange act assert, it is important to make it clear what code is for arranging, acting and asserting.

When testing a complex scenario, I am used to having multiple times the same action, every test. The arranging changes, and so does the assertion. But the action remains the same.

Recently I have encountered this code:

before do
    post 'somewhere'
end

it 'creates something' do
    expect 'something'.to be true
end

And I am not sure if this is a good practice. Arranging code gets in the middle of action and assertion when, for instance, we add contexts.

before do
    post 'somewhere'
end

[ some tests ]

context 'when a more complex scenario applies' do
    before do 
      [more complex arrangements]
    end

    it 'creates something more complex' do
        expect 'something'.to be true
    end
end

Is it a good practice to DRY these actions?

1

There are 1 best solutions below

0
sam On

Yes. This is still preferable (IMHO) because if you change the site, then you can change the code of all of your tests in just one place. Just make a helpers file and add your methods in here.

# spec/helpers.rb
module Helpers

  def method1(*args)
    # do something
  end

end

You can add it via rails_helper or in individual files:

require 'helpers'
RSpec.configure do |config|
  config.include Helpers
end

And then you just call them in your specs like any regular method.