Boring Rails

Tip: Testing multiple sessions in the same test with Capybara

:fire: Tiny Tips

Sometimes a feature in your application will involve a back-and-forth between multiple users. When it comes time to write an automated system test, you can easily simulate switching between users using Capybara’s using_session helper.

Instead of logging in and out or faking out another user making changes to the app, you can use multiple sessions within the same Capybara test.

This can be very useful for testing features like notifications, chat, or even multi-person workflows where different users have to take action to move a process forward.

Usage

There are a few options for controlling the session in Capybara.

You can set the session manually:

Capybara.session_name = "Test session #1"

But I prefer the using_session block helper, which will run any code inside the block in a separate session and then revert back to the original session when you leave the block.

Here is an example of how you could test a basic task management system where users can assign tasks to others to complete.

describe "Task Assignment", type: :system do

  it "allows users to assign tasks to other users" do
    login as: users(:kelly)

    visit "/tasks"

    click_on "Review deliverable"

    click_button "Assign to..."

    select "Sam", from: "Assignee"
    click_button "Save"

    expect(page).to have_content("Status: Pending")
    expect(page).to have_content("Assigned: Sam")

    using_session("Sam") do
      login as: users(:sam)

      visit "/tasks/me"
      expect(page).to have_content("Review deliverable")

      click_on "Review deliverable"
      click_on "Mark complete"
    end

    refresh

    expect(page).to have_content("Status: Completed")
  end
end

Additional Resources

Capybara Docs: Using Multiple Sessions

If you like these tips, you'll love my Twitter account. All killer, no filler.