Tutorial 10 – Background keyword in behave BDD
Welcome to the 10th article in Behave BDD series!
What you will Learn :
About ‘Background’ keyword
User story
Create feature file to capture scenarios
Background keyword
About ‘Background’ keyword
Background keyword is used to define some pre-conditions for all the scenarios. Many a times, we repeat the same ‘Given’ step in all the scenarios. Since ‘Given’ step is repeated in every scenario, we can move such repeated steps to the background, by grouping them under a ‘Background’ section.
User story
The user story or the requirement is that:
We have to launch www.amazon.in and click ‘Sign in’
Next we will enter our user id and click ‘Continue’
Next we enter our password and click ‘Sign-in’
Once we login, we will click ‘Your Orders’
We will see our ‘Orders’, ‘Open Orders’, ‘Cancelled Orders’
So we will write below 3 scenarios over here:
When I log in and go to order details page, I want to see my previous orders
When I log in and go to order details page, I want to see my open orders
When I log in and go to order details page, I want to see my cancelled orders
Create feature file to capture scenarios
Create a feature file and mention the 3 scenarios, see below
If you carefully notice the 3 scenarios, the below steps are repeated in each scenario
It is not advisable to repeat the steps inside the scenarios.
Background keyword
We will now write all the common steps as part of ‘Background’ keyword, see below. Delete all the common steps from the 3 scenarios. So we will be left with below. If you notice, the feature is more readable now. Each scenario is now focussing on what exactly we want to test as part of that scenario. All the common steps need not be written for every scenario
So the property of ‘Background’ keyword is that, when you run it, it will be executed before each and every scenario. So in this case, it would be executed 3 times since we have 3 scenarios.
Save the feature file
Create a step definition file
Save the step def file.
Run the feature file
Notice the console o/p
The o/p is exactly same as we were expecting. All the common steps that we wrote as part of ‘Background’ section get automatically attached to each and every scenario. If you notice, 24 steps passed (this is because there are 6 common steps as part of background and 2 steps in each of the 3 scenarios, so in total, 8 steps * 3 scenarios)
So this is how we use the ‘Background’ keyword.
Thank you for reading!