[rspec-users] Cannot log in/authenticate within RSpec Story

Ben Men lists at ruby-forum.com
Mon Jun 2 18:46:59 EDT 2008

I've been slamming my head against a wall for a while now, and would
like some help.  I believe this is session related.

I have a story that looks like:


    Given that a post exists
    And I am logged in
    When I visit the post details page
    Then there should be a link to add a new comment


I am using the following RSpec story functions to assist this scenario
(along with others):


  Given("I am logged in") do
    post '/login/login', {:name => 'domain\\username', :password =>
    follow_redirect if redirect?

  When "I visit the post details page" do

   Then "there should be a link to add a new comment" do
    response.should have_text(/.*Add New Comment.*/)


The "Add New Comment" text will only show up within the view if

The login controller looks like this:


  def login
    if request.get?
      session['username'] = nil
      # Split username on domain and alias
      split_username = params[:name].split('\\', 2)
      if split_username.length != 2
        flash[:notice] = "You did not enter a properly formatted domain
and alias"
        redirect_to :action => 'login'
        # Authenticate username and password
        domain = split_username[0]
        username = split_username[1]
        password = params[:password]
        isAuthenticated = authenticate(domain, username, password)
        if isAuthenticated
          # User has been authenticated
          session['username'] = username
          redirect_back({:controller => 'posts', :action => 'index'})
          flash[:notice] = "Incorrect username or password"
          redirect_to :action => 'login'


After the post to login/login occurs, I've attempted to check the
session variable everywhere I could think to, and it does not contain a
username in the data hash.

Additionally, I'm told that session is a nil object within the login
controller if I try something like:


  Given("I am logged in") do
    @lc = LoginController.new
    @lc.authenticate('domain', 'username', 'password')


I've also tried setting the session variable directly, but after that
particular Given .. do clause is finished, any settings I make directly
seem to be lost.

1. Can controllers within rspec stories set/get session data?
2. What is the scope of the persistence of sessions in rspec? (Scenario?
3. Any ideas on why my LoginController sets the session['username']
variable, only to have my PostsController unable to read it?

Also, keep in mind that the code works when I'm actually using the site,
but the rspec story fails because it's not displaying an "Add New
Comment" link when it should be due to the PostsController thinking that
the user isn't logged in.
Posted via http://www.ruby-forum.com/.

More information about the rspec-users mailing list