[rspec-users] [cucumber] accessing session variables

Balint Erdi lists at ruby-forum.com
Wed Mar 11 14:52:48 EDT 2009


I have the following simple scenario and the step definitions:

Scenario: Create album
  Given I am logged in as "pepito"
  When I go to my profile page

Given /^the user (.*) exists$/ do |login_name|
  User.find_by_login(login_name) || Factory(:user_with_password, :login
=> login_name)

Given /^I log in as (.*)$/ do |login_name|
  user = User.find_by_login(login_name)
  # it is supposed that the user was generated by the
:user_with_password fixture
  # that has the 'secret' password
  post "/session", :login => user.login, :password => 'secret'

Given /^I am logged in as "(.*)"$/ do |login_name|
  Given "the user #{login_name} exists"
  Given "I log in as #{login_name}"

When /^I go to (.+)$/ do |page_name|
  visit path_to(page_name)

def path_to(page_name)
  case page_name

  when /my profile page/i
    member_profile_path(:id => session[:user_id])

I receive the following error:

When I go to my profile page  #
  You have a nil object when you didn't expect it!
  The error occurred while evaluating nil.session (NoMethodError)

So it seems like the session is not accessible -or not this way- in the
step definitions. I finally came up with that workaround:

def path_to(page_name)
  case page_name

  when /my profile page/i
    member_profile_path(:id => User.first)

However, I am not at all content with this hack. It does not go to the
profile page of the logged in user but to the first one. This can be the
same -and in this scenario it is- but there is no guarantee for that.

I wonder if there is a way to retrieve things stored in the session.
Ideally I could even write:

  when /my profile page/i
      member_profile_path(:id => current_user)

Where current_user is defined in a helper class, and will also use a
session variable behind the scenes (I received an undefined method
"current_user" error when I tried this).

Could someone enlighten me about how to do this or whether this is
considered bad practice because current_user is more state-based (as
opposed to behavior-based_?

Thank you,
Posted via http://www.ruby-forum.com/.

More information about the rspec-users mailing list