3
votes

I am creating a web application with Ruby on Rails 3.1 (RC1). I am using Factory Girl, RSpec and Cucumber (with Capybara) for testing, but I am experiencing unexpected raised ActionDispatch::ClosedErrors some of the times (not every time) when I am creating new users (through the User model's create action). Below is the error message that I get:

Cannot modify cookies because it was closed. This means it was already streamed
back to the client or converted to HTTP headers. (ActionDispatch::ClosedError)

The error is raised when using these ways of creating users:

  • Creation using Factory Girl
    • Factory.create( :user )
    • Factory.build( :user ).save
  • Basic creation
    • User.create( { ... } )
    • User.new( { ... } ).save

What is funny is that they do work during some test, but not in others, and it does not seem random, although I cannot figure out the reason. Below is an excerpt from my code:

users_controller_spec.rb

require 'spec_helper'

def user
  @user ||= Factory.create( :user )
end

def valid_attributes
  Factory.attributes_for :user
end

describe UsersController do

  describe 'GET index' do
    it 'assigns all users as @users' do
      users = [ user ] # The call to user() raises the error here
      get :index
      assigns[ :users ].should == users
    end
  end

  describe 'GET show' do
    it 'assigns the requested user as @user' do
      get :show, id: user.id # The call to user() raises the error here
      assigns[ :user ].should == user
    end
  end

However, the error is not raised in the following code block:

describe 'GET edit' do it 'assigns the requested user as @user' do get :edit, id: user.id # This raises no error assigns[ :user ].should == user end end

Any other method below this does not raise the error, even though I am creating users in the exact same way.

Any suggestions to what I might be doing wrong would be greatly appreciated!

3

3 Answers

2
votes

This is due to the way rails 3 streams the response now. They posted a fix in edge for the same issue in flash but not in cookies yet. For now I have turned off my request specs. I am going to look at the problem this weekend if no one gets to it before then.

https://github.com/rails/rails/issues/1452

1
votes

Just so we don't have to follow links, here's my modified version of the authlogic workaround:

class User < ActiveRecord::Base
  acts_as_authentic do |c|
    c.maintain_sessions = false if Rails.env == "test"
  end    
end

Rather than deal with ensuring session management on every .save call, I just turn them off if I'm testing.