What is the best way to access instances of a Cucumber instance to form nested classes inside steps?

This is a simple question. I have Cucumber steps, for example:

Given /We have the test environment/ do @user = # Create User model instance @post = # Create Post model instance # etc... end 

At the next stage, I use my own classes, they simplify the testing process:

 Then /all should be fine/ do # MyValidatorClass has been defined somwhere in features/support dir validator = MyValidatorClass.new validator.valid?.should be_true end 

Inside the MyValidatorClass instance, I look at the above instance variables @user, @post, etc.

What is the best and easiest way to access Cucumber variables from an instance of MyValidatorClass?

 class MyValidatorClass def valid? @post @user end end 

Now I manually passed all the arguments to the MyValidatorClass instance:

 validator = MyValidatorClass.new @user, @post 

But I think this goal is bad. I need something more transparent, because we use Ruby, therefore!

What is the best way to do this?

+4
source share
2 answers

I found a possible soul. You just need to go from instance variables to class variables:

 Given /We have the test environment/ do @@user = # Create User model instance @@post = # Create Post model instance # etc... end Then /all should be fine/ do # MyValidatorClass has been defined somwhere in features/support dir validator = MyValidatorClass.new validator.valid?.should be_true end ... class MyValidatorClass def valid? @@post @@user end end 
0
source

Instance variables defined in World are available only within World. Step definitions belong to the world. You must put MyValdatorClass inside World World{MyValdatorClass.new} . After the instance variables defined earlier in this script, stepdefs become available in this class and other step definitions in the same script.

Some other thoughts that relate to your question:


If you have the Given we have the test environment step, then:

  • you will duplicate it in all feaures
  • your functions become longer and less readable due to unnecessary data to read the current function.
  • setting up unnecessary environmental information will take some time

An easier way to create instances is to add a helper method that will create them for you:

 module InstanceCreator def user @user ||= # Create user instance in World end #etc end World(InstanceCreator) 

Then you just use this user when you need it (without any @ or @@).

If you need anything else other than instantiation, use hooks

Your scripts should be natural. You do not have to spoil them the steps you need to get the level of automation.


It is better to have a regex starting with ^ and ending with $. Without this, the definition of the step becomes too flexible. Your first step definition will also correspond to Given We have the test environment with some specifics .

+2
source

All Articles