How to make a cucumber test work with multiple browser sessions

Imagine you want to write a cucumber test for a user-to-user chat. To do this, you need the test to work with several browser sessions, logged in as separate users, at the same time.

Luckily, Capybara makes this relatively easy:

Scenario:

Scenario: Alice and Bob can chat
  Given Alice, Bob, and a chat session
  When I am signed in as "Alice"
    And I go to the chat
    And I am signed in as "Bob" [session: bob]
    And I go to the chat [session: bob]
    And I send the message "Hello, this is Alice!"
  Then I should see "Hello, this is Alice!" within the chat
    And I should see "Hello, this is Alice!" within the chat [session: bob]

Capybara has a method Capybara.using_session allowing you to perform steps in different browser sessions, so all you need is the following:

When(/^(.*) \[session: (.*?)\]$/) do |step_text, session_name|
  Capybara.using_session(session_name) do
    step(step_text)
  end
end

Effect on other step definitions

Be careful that this also affects other steps. For example, we often use something like this for authentication:

module AuthenticationSteps
  def sign_in(user)
    sign_out if @current_user # BROKEN!
    login_as user
    @current_user = user
  end

  # ...
end
World(AuthenticationSteps)

This will not work, since now there is no longer one logged in user, but potentially several.

Work around this with something like:

module AuthenticationSteps
  def reset_signed_in_users
    @current_users = {}
  end

  def sign_in(user)
    sign_out if @current_users[Capybara.current_session]
    login_as user
    @current_users[Capybara.current_session] = user
  end

  # ...
end
World(AuthenticationSteps)

Before do
  reset_signed_in_users
end
Tobias Kraze About 4 years ago