Posted 5 months ago. Visible to the public.

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: 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
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Tobias Kraze
Last edit:
4 months ago
by Tobias Kraze
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more