Search code examples
cucumberhookcucumber-java

How to read tag's value in cucumber hooks method


I am passing tags for my cucumber BeforeActions hooks @Before that I want to use as a parameter inside the Before method.

@Before("@requireLogin")
    public void defaultLogin() {
          do login here;
    }

@Before("@newUserA")
    public void login() {
          do login with a user called "newUserA";
    }

In first @Before I am using default Login user but in another @Before I want to send a tag as a hint to use that user as a username for login.

Now I am not sure how do I read that "newUserA" inside login method. Any help would be appreciated.


Solution

  • You should not use a tag to login. Login is business functionality and needs to be mentioned in each scenario where it is required. If you have lots of scenarios that need you to be logged in you can put the login step in the background. e.g.

    Feature: Admin xxx
    
    Background:
      Given I am logged in as an admin
    
    Scenarios Do foo
      When I foo
       ...
    
    Scenario: Do bar
      When I bar
    

    You can then use a number of different login steps to clearly specify the different needs you might have, and if you are really clever you can have each step def delegate the work to a helper method so you avoid duplicate code e.g.

    # Login Steps
    
    Given "I login as an admin" do
      @i = create_user(role: 'admin')
      login as: @i
    end
    
    Given "I login as Fred" do
      @fred = create_user(first_name: 'Fred')
      login as: @i
    end
    
    Given "Fred is logged in" do
      # this one assumes that Fred has already been created
      login as: @fred
    end
    
    ...
    

    The actor (person who is doing stuff) and whether or not they are logged in, is far too important to be left out of the scenario language. I'd strongly suggest you change your approach here and not use tagging for this. @