Warden To Login/Logout Within Your Cucumber Tests

Reading Time: 2 minutes

Recently we had to implement some tests to see if the user session had expired, and to do that we used Capybara to open a new window, follow the logout link, close that window and then go back to the first window, which was already logged in.... kind of messy right? So then I decided to use Warden instead, with the intention of tricking the app to think the user session had expired, which would be an easy and straight forward solution.

I. Load Helpers

The first thing that needs to be done is to load Warden's helpers, so let's create a warden.rb file under our /features/support directory with the following code inside:

World Warden::Test::Helpers
After { Warden.test_reset! }

Provides helper methods to Warden for testing, such as Warden.test_reset and Warden.on_next_request

World Warden::Test::Helpers

Loads the Warden helpers in the Cucumber 'world' so we can access login_as and logout methods.

After { Warden.test_reset! }

We need to reset Warden after each test in order to make it work, so after every scenario a Warden.test_reset! should be called.

II. Login/Logout Steps

Now that our helpers are loaded, we can simply login by using login_as(user, options = {}) and logout by using logout, simple as that. So let's create features/step_definitions/user_steps.rb with the following:

Given /^I am logged in as a user$/ do
  @current_user = User.create!(:username => 'user', :password => 'password')
  login_as(@current_user, :scope => :user)

Given /^I log out$/ do

And that's it. Pretty easy right?

In Conclusion

This built-in test helpers are useful because they allow us to login or logout without using the UI, but this might be not so useful because signing in with Capybara is more like a real world scenario, and we want to keep our integration tests as close to reality as possible. But signing in/out with that can save us some valuable time if we have a big test suite, which might prove useful too, regarding test run times.

Know more about us!

You May Also Like
Read More


Reading Time: 4 minutes Authorization determines which actions a user can perform on an application There are a lot of alternatives which…