How to organize Behat features folder and context classes to share same steps?

80 Views Asked by At

I have 2 features, one context class for each feature. The 2 features have common steps. I have created a Trait to put into the common steps. But Behat says the steps are already defined...

I could repeat the common steps into each context with different names, but I don't want to repeat code.

enter image description here

behat.yml :

default:
  suites:
    web:
      contexts:
        - RegisterVehcileContext
        - ParkVehicleContext
1

There are 1 best solutions below

0
Barry On

Create a VehicleInMyFleetContext that contains the steps VehicleInMyFleetTrait does. Features can use steps from any Context in their context.

Maybe think ahead more as "Vehicle In My Fleet" already sounds like a step, maybe FleetContext.

Add this new context to your contexts:

default:
  suites:
    web:
      contexts:
        - RegisterVehcileContext
        - ParkVehicleContext
        - FleetContext

I prefer to share contexts so that any step in features or via code can call any other step for reusue.

However, if you wanted the opposite where features only use their own dedicated context and not another... then you will need to create and use multiple profiles:

RegisterVehcile:
  suites:
    web:
      contexts:
        - RegisterVehcileContext
ParkVehicle:
    web:
      contexts:
        - ParkVehicleContext

see configuration of behat.yml for more information on profiles and identifying your profile with command line tool.

Different profiles are often used to implement the same feature but with different contexts, i.e. one uses a REST API directly whereas another uses the same REST API but via selenium instead.