And / But Usage Rules

And and But are supporting keywords in Gherkin.

And But Usage Rules in Cucumber

They exist purely to improve readability and avoid repetition of Given, When, and Then.

They do not introduce new behavior types.

And / But Usage Rules in Cucumber: Full Explanation

The And and But keywords are supporting keywords in Gherkin. They do not introduce new behavior types, and they do not change the execution model of Cucumber. Their purpose is readability. They help feature files avoid repetitive use of Given, When, and Then while still preserving the meaning of the previous step type. In simple terms, And continues the previous keyword, and But continues the previous keyword while expressing a contrast, exception, or negative expectation.

This distinction is important because many beginners assume that And and But are separate categories of behavior. They are not. Gherkin has primary behavioral structure through Given, When, and Then. Given sets context, When triggers the action, and Then verifies the outcome. And and But only make the scenario read more naturally. They inherit meaning from the keyword that came immediately before them.

For example, if And follows a Given step, it behaves like another Given. If And follows a When step, it behaves like another When. If And follows a Then step, it behaves like another Then. The same rule applies to But. This inheritance is the foundation of correct And and But usage. Once a team understands this rule, the feature file becomes easier to write, easier to review, and easier to automate.

And and But are especially useful in scenarios where several related preconditions, actions, or outcomes need to be expressed. Without these supporting keywords, a scenario may repeat Given or Then multiple times and become awkward to read. With And and But, the scenario sounds closer to natural language while keeping the structure clear.

Why And and But Exist

Gherkin is designed to be readable by business stakeholders, testers, developers, and automation engineers. A scenario should tell a clear behavior story. Repeating the same keyword many times can make the scenario feel mechanical. For example, "Given the user is logged in, Given the user has admin privileges, Given the account is active" is technically understandable, but it reads poorly. Using And improves the flow: "Given the user is logged in, And the user has admin privileges, And the account is active."

The purpose is not to shorten the scenario at any cost. The purpose is to make the scenario more readable without changing its meaning. The reader should still understand which lines are context, which lines are actions, and which lines are outcomes. If And or But makes that unclear, the scenario should be rewritten with Given, When, or Then.

But exists for a slightly different readability purpose. It is useful when the expected result includes a contrast or exception. For example, "Then the payment should be declined, But the account balance should remain unchanged" reads naturally because the second outcome contrasts with a possible unwanted side effect. But tells the reader that something should not happen or that a related state should remain unaffected.

How And Works

And inherits the meaning of the previous keyword. If the previous keyword is Given, the And line is also treated as a Given-style precondition. If the previous keyword is When, the And line is treated as part of the action phase. If the previous keyword is Then, the And line is treated as an additional expected result.

Given the user is logged in
And the user has admin privileges

Both lines describe context. The user is logged in, and the user has admin privileges before the behavior occurs. Even though the second line begins with And, it does not become a new behavior type. It is still part of the Given context. The step definition may be annotated with @Given, because Cucumber treats the step text as a Given-type step in meaning and structure.

And is also useful after When when the action naturally has multiple related parts. For example, a login flow may include entering a username, entering a password, and clicking the login button. In a technical automation scenario, these can appear as multiple When-related steps. However, teams should be careful. If too many And steps follow When, the scenario may become too procedural and UI-driven. A higher-level action such as "When the user logs in" may be better if the field-level details are not important to the behavior.

After Then, And helps list multiple expected outcomes. For example, after a successful login, the dashboard should be displayed and the welcome message should be visible. Both are outcomes. Using Then followed by And is readable and natural.

How But Works

But also inherits the meaning of the previous keyword, but it adds a sense of contrast. It is commonly used for negative expectations or exceptional outcomes. But is especially useful in Then sections because many business rules include something that should not happen.

Then the payment should be declined
But the account balance should remain unchanged

Both lines are treated as Then steps. The first line verifies the main outcome: payment is declined. The second line verifies a related negative or protective outcome: the account balance is not changed. The word But makes the relationship clearer than And because it signals contrast.

But can also follow Given, although this is less common. For example, "Given user is logged in, But user does not have Admin role" describes a context with a restriction. This is valid if it reads clearly. However, teams should avoid using But randomly. It should express a real contrast or exception, not simply replace And for variety.

The best use of But is when it improves meaning. If a step says what must not happen, But often reads better than And. For example, "Then login page should appear, But dashboard should not be visible" communicates both the expected navigation and the negative validation clearly.

Where And and But Can Be Used

And and But can follow any primary Gherkin keyword. They can follow Given, When, or Then. What matters is the previous keyword. If And follows Given, it continues context. If And follows When, it continues action. If And follows Then, it continues outcome. But follows the same inheritance rule while adding contrast.

When the user submits the form
And the system validates the input

In this example, And continues the When phase. The system validation is part of the action or event flow. But if the next line is an expected result, Then should be used instead. For example, "Then validation errors should be displayed" is an outcome and should not be hidden behind And after When.

This is the most important practical rule: if the step changes behavior type, use the correct core keyword. Do not use And or But to move from context to action, or from action to outcome. The reader should never have to guess whether an And line is setup, action, or verification.

Rule 1: Do Not Replace Core Keywords

A scenario should not start with And or But. These keywords depend on the previous keyword, so starting a scenario with And creates unclear meaning. A scenario should begin with a primary keyword such as Given when context is being established.

And the user is logged in

This is poor usage because there is no previous keyword to inherit meaning from. A better version is:

Given the user is logged in
And the user has a valid session

Here, Given defines the context and And adds another related precondition. The scenario reads naturally and the structure is clear. And supports the core keyword; it does not replace it.

Rule 2: Avoid Multiple When Actions

Technically, And can follow When many times. But too many When-related actions can make a scenario procedural and hard to understand. A scenario should usually focus on one main behavior. If a scenario logs in, updates a profile, changes a password, checks notifications, and logs out, it may be testing too much.

When the user logs in
And the user updates profile

This may be a problem if login and profile update are two separate behaviors. A better approach is often to split them into separate scenarios. One scenario validates login. Another scenario validates profile update, with login expressed as a Given precondition.

Using one main When keeps scenarios focused. It also makes failures easier to interpret. If a long scenario fails, it may be unclear which behavior broke. Smaller scenarios provide better feedback.

Rule 3: Use And for Additional Conditions, Not New Behavior

And should continue the same phase of the scenario. It should not introduce a different behavior type. For example, if a scenario says "Given the user is logged in, And the user clicks logout", the And line is wrong because clicking logout is an action, not context.

Given the user is logged in
And the user clicks logout

A better version is:

Given the user is logged in
When the user logs out

This version is clearer because it uses Given for context and When for action. The structure tells the reader exactly what is already true and what event triggers the behavior.

Rule 4: Use But for Negative or Exceptional Outcomes

But is strongest when it expresses something that should not happen or something that remains unchanged. It improves readability in negative scenarios because it highlights contrast. For example:

Then the order should fail
But the payment should not be charged

This is clearer than using And because the second outcome is a protective expectation. The order fails, but the payment is not charged. The word But helps the reader understand that the second outcome prevents an unwanted side effect.

But should still be used with discipline. It should not appear randomly just to vary wording. If there is no contrast, And may be better. If the step changes from outcome to action, Then or When should be used instead.

Good vs Bad Examples

A bad example is UI-driven and mixes technical actions into setup:

Given I open the browser
And I click login

This reads like automation instructions rather than behavior. It also uses And after Given for an action. A better behavior-driven version is:

Given the user has valid credentials
And the account is active

Both lines are context. They describe the state required before the user logs in. This is the correct use of And because it continues the Given phase with another precondition.

Readability Guidelines

Use And to avoid repeating Given, When, or Then when several related statements belong to the same phase. This makes scenarios smoother to read. However, do not chain too many And steps. A long chain may signal that the scenario is too detailed or covers too much behavior.

Keep each step concise. A step should express one idea. If a step contains several actions connected by "and" inside the sentence, it may need to be split or rewritten at a higher level. For example, "When the user enters details and selects country and accepts terms and clicks register" is hard to read. "When the user completes registration" may be clearer if the details are not the focus.

Use consistent phrasing across feature files. If one file says "user logs in" and another says "user signs into the application", the team may create duplicate step definitions for the same idea. A shared vocabulary improves reuse and keeps the suite maintainable.

Common Mistakes

One common mistake is using And to hide multiple actions. This makes the scenario look shorter but does not make it better. If each And represents a major user action, the scenario may need to be split or abstracted.

Another mistake is using But randomly. But should indicate contrast, exception, or negative expectation. If the second line is simply another positive outcome, And may be clearer. For example, "Then dashboard should be visible, And welcome message should be displayed" reads better than using But because there is no contrast.

Overusing And can create long scenarios. Long scenarios are harder to read, harder to automate, and harder to debug. If a scenario contains many And steps across Given, When, and Then, review whether the behavior can be split into smaller scenarios.

Mixing context and action in one step is also a problem. "Given the user is logged in and clicks checkout" combines state and action. It should be separated into "Given the user is logged in" and "When the user checks out" if checkout is the behavior being tested.

Practical Example: And with Given

And works well with Given when multiple preconditions are needed. The following scenario establishes that the application is launched and the user is on the login page before credentials are entered.

Feature: Login

Scenario: Valid Login
  Given user launches the application
  And user is on the login page
  When user enters valid credentials
  Then dashboard should be displayed
@Given("user launches the application")
public void launchApplication() {
    driver.get("https://example.com");
}

@Given("user is on the login page")
public void loginPage() {
    Assert.assertTrue(driver.getTitle().contains("Login"));
}

The And line is treated as another Given-style setup step. It does not introduce a new action phase. It simply adds another context condition.

Practical Example: And with When

And can follow When when the action phase naturally has related sub-actions. In login automation, entering username, entering password, and clicking the login button are often written as separate When-related steps.

Scenario: Login
  Given user opens login page
  When user enters username "admin"
  And user enters password "admin123"
  And user clicks login button
  Then dashboard should appear
@When("user enters username {string}")
public void enterUsername(String username) {
    driver.findElement(By.id("username")).sendKeys(username);
}

@When("user enters password {string}")
public void enterPassword(String password) {
    driver.findElement(By.id("password")).sendKeys(password);
}

@When("user clicks login button")
public void clickLogin() {
    driver.findElement(By.id("loginBtn")).click();
}

This is technically valid. In a more business-focused feature file, the team may choose to combine these into a single step such as "When the user logs in with valid credentials." The better wording depends on what the scenario is trying to communicate.

Practical Example: And with Then

And is often useful after Then when one action produces several expected outcomes. For example, after the dashboard opens, the dashboard should be visible, the welcome message should appear, and the logout button should exist.

Scenario: Dashboard Verification
  Given user logs in
  When dashboard opens
  Then dashboard should be visible
  And welcome message should be displayed
  And logout button should exist

All three final lines are outcome checks. The first uses Then, and the following two use And to avoid repeating Then. This is a clean use of And because the meaning remains consistent.

Practical Example: But with Then

But is especially useful in negative scenarios. For invalid login, the system should show failure, but it should not crash. The word But makes the contrast clear.

Scenario: Invalid Login
  Given user is on login page
  When user enters invalid credentials
  Then login should fail
  But application should not crash
@Then("login should fail")
public void loginShouldFail() {
    Assert.assertTrue(driver.findElement(By.id("error")).isDisplayed());
}

@Then("application should not crash")
public void applicationShouldNotCrash() {
    Assert.assertFalse(
        driver.getPageSource().contains("500 Internal Server Error")
    );
}

The But step is still a Then-style verification. It checks a negative expectation: the application should not crash. This is a strong use of But because it highlights an important protective outcome.

More Real Project Examples

A restricted user scenario can use But after Given to describe a limiting context:

Scenario: Restricted User
  Given user is logged in
  But user does not have Admin role
  When user opens Admin page
  Then access should be denied

Product search can use And in the action and outcome phases:

Scenario: Product Search
  Given user opens home page
  When user enters "Laptop"
  And clicks Search
  Then products should be displayed
  And result count should be greater than zero

Shopping cart scenarios can use And for related actions, but teams should be careful not to make the scenario too long:

Scenario: Shopping Cart
  Given user is on product page
  When user adds product to cart
  And updates quantity to 2
  And applies coupon
  Then total price should be updated

If updating quantity and applying coupon are separate behaviors, this scenario may need to be split. If the purpose is to validate the combined cart calculation, the sequence may be acceptable. Context matters.

Complete Example with And and But

A complete invalid login scenario can combine Given, When, Then, And, and But. The scenario launches the application, opens login, enters data, clicks login, verifies the error, confirms the login page remains open, and ensures the dashboard is not displayed.

Feature: Login Validation

Scenario: Invalid Login
  Given user launches application
  And user opens login page
  When user enters username "admin"
  And user enters password "wrong123"
  And user clicks Login
  Then error message should be displayed
  And login page should remain open
  But dashboard should not be displayed
@Then("error message should be displayed")
public void verifyErrorMessage() {
    Assert.assertTrue(driver.findElement(By.id("error")).isDisplayed());
}

@Then("login page should remain open")
public void verifyLoginPage() {
    Assert.assertTrue(driver.getCurrentUrl().contains("login"));
}

@Then("dashboard should not be displayed")
public void verifyDashboardNotDisplayed() {
    Assert.assertFalse(driver.getCurrentUrl().contains("dashboard"));
}

This example shows the practical use of And and But, but it also shows why discipline is needed. If the When section grows too long, the scenario can become procedural. If the Then section includes many checks, the team should confirm that all checks belong to the same behavior.

Interview-Ready Understanding

In interviews, the most important point is that And and But are supporting keywords. They inherit meaning from the previous step. They are used for readability, not behavior change. They should not be used to introduce a new type of step. If the behavior type changes, use Given, When, or Then.

A strong answer should also mention that But is useful for negative expectations or contrast, while And is useful for additional preconditions, actions, or outcomes that belong to the same phase. The candidate should explain that overusing And can create long scenarios and that multiple When actions should be avoided when they represent separate behaviors.

Team Standards for And and But

In real Cucumber projects, teams should agree on standards for using And and But. Without standards, feature files can become inconsistent. One tester may use And for every extra line, another may repeat Given and Then, and another may use But randomly. The scenarios may still execute, but the suite becomes harder to read and maintain. A simple team guideline prevents this problem.

A useful standard is to use And only when the new step clearly belongs to the same phase as the previous step. If the previous step is Given, the And step should also describe context. If the previous step is When, the And step should continue the same action flow. If the previous step is Then, the And step should describe another outcome. If the new step does not fit the same phase, the writer should use Given, When, or Then instead.

Another useful standard is to limit long chains. If a scenario has five or six And steps, it should be reviewed. Sometimes the scenario is still valid, especially when several related outcomes must be checked. But often a long chain indicates that the scenario is too detailed, too procedural, or trying to cover too many behaviors. Reviewing long And chains improves feature file quality over time.

Teams should also decide how they want to use But. A practical guideline is to reserve But for contrast, exception, or negative verification. This keeps the keyword meaningful. If But is used for every second outcome, it loses its value. When readers see But, they should immediately understand that the scenario is highlighting something that should not happen or something that remains different from what might be expected.

During code review, reviewers should check whether And and But improve readability. If they make the scenario less clear, the steps should be rewritten. Reviewers should also check whether And is hiding a behavior transition. For example, an And after Given that performs a user action should be changed to When. An And after When that verifies a result should be changed to Then. These small corrections keep the suite aligned with BDD principles.

Good use of And and But makes Gherkin sound natural without weakening structure. The best feature files read like clear business examples, not like technical scripts. And and But help achieve that readability when they are used as supporting keywords, not as substitutes for thinking carefully about context, action, and outcome.

Quick Reference Notes

1. Purpose of And and But

And and But are supporting keywords in Gherkin.

They exist purely to improve readability and avoid repetition of Given, When, and Then.

They do not introduce new behavior types.

2. How And Works

And inherits the meaning of the previous keyword.

Example:

Given the user is logged in
And the user has admin privileges

Both lines are treated as Given steps.

3. How But Works

But is used to express contrast or exception, while still inheriting the previous keyword.

Example:

Then the payment should be declined
But the account balance should remain unchanged

Both lines are treated as Then steps.

4. Where And / But Can Be Used

They can follow any primary keyword:

  • Given → And / But
  • When → And / But
  • Then → And / But

Example:

When the user submits the form
And the system validates the input

5. Recommended Usage Rules

Rule 1: Do Not Replace Core Keywords

Avoid starting scenarios only with And.

Bad:

And the user is logged in

Good:

Given the user is logged in
And the user has a valid session

Rule 2: Avoid Multiple When Actions

Technically allowed, but discouraged.

Bad:

When the user logs in
And the user updates profile

Better:

Split into separate scenarios.

Rule 3: Use And for Additional Conditions, Not New Behavior

Bad:

Given the user is logged in
And the user clicks logout

Good:

Given the user is logged in
When the user logs out

Rule 4: Use But for Negative or Exceptional Outcomes

But improves clarity when expectations are contrasted.

Example:

Then the order should fail
But the payment should not be charged

6. Good vs Bad Examples

Bad (UI-driven):

Given I open the browser
And I click login

Good (Behavior-driven):

Given the user has valid credentials
And the account is active

7. Readability Guidelines

  • Prefer And over repeating Given
  • Do not chain too many And steps
  • Keep steps concise
  • Use consistent phrasing

8. Common Mistakes

  • Using And to hide multiple actions
  • Using But randomly
  • Overusing And to create long steps
  • Mixing context and action in one step

9. Interview-Ready Summary

  • And and But are supporting keywords
  • They inherit meaning from the previous step
  • Used for readability, not behavior change
  • Avoid using them to introduce actions
  • But highlights exceptions or contrasts

10. Golden Rule

If the step changes behavior type, use Given/When/Then—not And/But.