Cyril Duchon-Doris
Cyril Duchon-Doris

Reputation: 13949

How to run a Cucumber Background step once for all Scenarios under the same feature?

In Cucumber, is it possible to run a Background step for the whole feature? So it doesn't get repeated every scenario?

I am running some tests on a search engine, and I need to pre-seed the search engine with test data. Since this data can be quite long to generate and process (I'm using Elasticsearch and I need to build the indices), I'd rather do this background only once, but only for all tests under the same feature.

Is it possible with Cucumber?

Note that I am using MongoDB, so I don't use transactions but truncation, and I believe I have DatabaseCleaner running automatically after each test, that I suppose I'll have to disable (maybe with an @mention?)

EDIT :

Yes I'm using Cucumber with Ruby steps for Rails

EDIT2 : concrete examples

For this I pre-seed the search engine with a dozen of results, and I run all those tests that are based on the same inputs. I often have "example" clauses that just do something slightly different, but based on the same seeding

Upvotes: 2

Views: 1393

Answers (2)

diabolist
diabolist

Reputation: 4099

There are a number of approaches for doing this sort of thing:

  1. Make the background task really fast.

Perhaps in your case you could put the search data outside of your application and then symlink it into the app in your background step? This is a preferred approach.

  1. Use a unit test tool.

Consider if you really get any benefit out of having scenarios to 'test' search. If you don't use a tool that allows you greater control because your tests are being written in a programming language

  1. Hack cucumber to work in a different way

I'm not going to go into this, because my answer is all about looking at the alternatives

For your particular example of testing search there is one more possibility

  1. Don't test at all

Generally search engines are other peoples code that we use. They have thousands of unit tests and tens of thousands of happy customers, so what value do your additional tests bring?

Upvotes: 1

Dave Schweisguth
Dave Schweisguth

Reputation: 37617

Supposing the search data is a meaningful part of the scenario, something that someone reading the feature should know about, I'd put it in a step rather than hide it in a hook. There is no built-in way of doing what you want to do, so you need to make the step idempotent yourself. The simplest way is to use a global.

In features/step_definitions/search_steps.rb:

$search_data_initialized = false

Given /^there is a foo, a bar and a baz$/ do
  # initialize the search data
  $search_data_initialized = false
end

In features/search.feature:

Feature: Search

  Background:
    Given there is a foo, a bar and a baz

  Scenario: User searches for "foo"
  ...

Upvotes: 1

Related Questions