升级到 Rails 3.1 后,许多使用 test_sign_in 的 rpsec 测试失败,可能是 cookie 问题?

发布于 2024-12-05 20:18:44 字数 5842 浏览 2 评论 0原文

我已经升级到 Rails 3.1,一切似乎都工作正常。但测试(RSpec)无论如何都会失败,例如以下测试:

describe "for admin user" do

  before(:each) do
    @city = Factory(:city)
    @user = Factory(:user)
    @business = Factory(:business, :user_id => @user.id, 
                        :city_id => @city.id)
    @admin = test_sign_in(Factory(:user, :email => "[email protected]", 
                                  :admin => true))
  end

  it "should have an edit link for all businesses in show city" do
    get :show, :id => @city
    response.should have_selector('a',
      :href => "/businesses/#{@business.id}-Factory-business-city-Factory-business/edit")
  end
end

这在 Rails 3.0.8 中运行良好,但现在测试失败了。测试日志显示:

[1m[35mSQL (0.2ms)[0m INSERT INTO users (admin, created_at, email加密密码名称updated_at)值(1, '2011-09-21 10:30:30', '[电子邮件受保护]', '68f8a34e0243a642662fe2b6ea8ed7c714d042750a66ce542f2df288caefac32', '管理员名称', '6df34c304d79437d495e60d2d34e1028489731afa96690efbc25c714224edb1f', '2011-09-21 10:30:30')

由 CitiesController 处理#show as HTML [1m[35m用户负载 (0.2ms)[0m SELECT users.* FROM users WHERE users.id IS NULL LIMIT 1

[1m[36mCity Load (0.2ms)[0m [1mSELECT 城市.* FROM 城市 WHERE 城市.id = 942 LIMIT 1[0m

[1m[35mCity Load (0.2ms)[0m SELECT 城市.* FROM 城市 WHERE 城市.id = 942 LIMIT 1

[1m[36mCity Load (0.2ms)[0m [1mSELECT cities.* FROM cities WHERE cities.id = 942 LIMIT 1[0m

[1m[36m用户负载(0.2ms)[0m [1mSELECT users.* FROM users WHERE users.id IS NULL LIMIT 1[0m

所以,似乎没有用户 ID (NULL),但管理员之前已正确创建。这可能是 cookie 问题吗?

我的 Gemfile 中的测试组是:

group :test do
  gem 'rspec', '2.6.0'
  gem 'rspec-rails', '2.6.1'
  gem 'webrat', '0.7.3'
  gem 'factory_girl_rails', '1.0'
  gem 'spork', '~> 0.9.0.rc'
end

我的 test.rb 是

Project::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # The test environment is used exclusively to run your application's
  # test suite.  You never need to work with it otherwise.  Remember that
  # your test database is "scratch space" for the test suite and is wiped
  # and recreated between test runs.  Don't rely on the data there!
  config.cache_classes = true

  # Configure static asset server for tests with Cache-Control for performance
  config.serve_static_assets = true
  config.static_cache_control = "public, max-age=3600"

  # Log error messages when you accidentally call methods on nil
  config.whiny_nils = true

  # Show full error reports and disable caching
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Raise exceptions instead of rendering exception templates
  config.action_dispatch.show_exceptions = false

  # Disable request forgery protection in test environment
  config.action_controller.allow_forgery_protection    = false

  # Tell Action Mailer not to deliver emails to the real world.
  # The :test delivery method accumulates sent emails in the
  # ActionMailer::Base.deliveries array.
  config.action_mailer.delivery_method = :test

  # Use SQL instead of Active Record's schema dumper when creating the test database.
  # This is necessary if your schema can't be completely dumped by the schema dumper,
  # like if you have constraints or database-specific column types
  # config.active_record.schema_format = :sql

  # Print deprecation notices to the stderr
  config.active_support.deprecation = :stderr

  # Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets
  config.assets.allow_debugging = true
end

这是我的 spec_helper:

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'rubygems'
require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However, 
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  ENV["RAILS_ENV"] ||= 'test'
  unless defined?(Rails)
    require File.dirname(__FILE__) + "/../config/environment"
  end
  require 'rspec/rails'

  # Requires supporting files with custom matchers and macros, etc,
  # in ./support/ and its subdirectories.
  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

  Rspec.configure do |config|
    # == Mock Framework
    #
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
    #
    # config.mock_with :mocha
    # config.mock_with :flexmock
    # config.mock_with :rr
    config.mock_with :rspec

    config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, comment the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true

    ### Part of a Spork hack. See http://bit.ly/arY19y
    # Emulate initializer set_clear_dependencies_hook in 
    # railties/lib/rails/application/bootstrap.rb
    ActiveSupport::Dependencies.clear

    def test_sign_in(user)
      controller.sign_in(user)
    end
  end
end

Spork.each_run do
end

谢谢您的建议/答案!

I have upgraded to Rails 3.1 and everything seems to work fine. But the tests (RSpec) fail anyhow, e.g. the following one:

describe "for admin user" do

  before(:each) do
    @city = Factory(:city)
    @user = Factory(:user)
    @business = Factory(:business, :user_id => @user.id, 
                        :city_id => @city.id)
    @admin = test_sign_in(Factory(:user, :email => "[email protected]", 
                                  :admin => true))
  end

  it "should have an edit link for all businesses in show city" do
    get :show, :id => @city
    response.should have_selector('a',
      :href => "/businesses/#{@business.id}-Factory-business-city-Factory-business/edit")
  end
end

This worked fine with Rails 3.0.8, but now the test fails. Test log says:

[1m[35mSQL (0.2ms)[0m INSERT INTO users (admin, created_at, email, encrypted_password, name, salt, updated_at) VALUES (1, '2011-09-21 10:30:30', '[email protected]', '68f8a34e0243a642662fe2b6ea8ed7c714d042750a66ce542f2df288caefac32', 'Admin Name', '6df34c304d79437d495e60d2d34e1028489731afa96690efbc25c714224edb1f', '2011-09-21 10:30:30')

Processing by CitiesController#show as HTML
[1m[35mUser Load (0.2ms)[0m SELECT users.* FROM users WHERE users.id IS NULL LIMIT 1

[1m[36mCity Load (0.2ms)[0m [1mSELECT cities.* FROM cities WHERE cities.id = 942 LIMIT 1[0m

[1m[35mCity Load (0.2ms)[0m SELECT cities.* FROM cities WHERE cities.id = 942 LIMIT 1

[1m[36mCity Load (0.2ms)[0m [1mSELECT cities.* FROM cities WHERE cities.id = 942 LIMIT 1[0m

[1m[36mUser Load (0.2ms)[0m [1mSELECT users.* FROM users WHERE users.id IS NULL LIMIT 1[0m

So, it seems there is no user id (NULL), but the admin was created correctly before. Might this be a cookie problem?

The test group in my Gemfile is:

group :test do
  gem 'rspec', '2.6.0'
  gem 'rspec-rails', '2.6.1'
  gem 'webrat', '0.7.3'
  gem 'factory_girl_rails', '1.0'
  gem 'spork', '~> 0.9.0.rc'
end

My test.rb is

Project::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # The test environment is used exclusively to run your application's
  # test suite.  You never need to work with it otherwise.  Remember that
  # your test database is "scratch space" for the test suite and is wiped
  # and recreated between test runs.  Don't rely on the data there!
  config.cache_classes = true

  # Configure static asset server for tests with Cache-Control for performance
  config.serve_static_assets = true
  config.static_cache_control = "public, max-age=3600"

  # Log error messages when you accidentally call methods on nil
  config.whiny_nils = true

  # Show full error reports and disable caching
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Raise exceptions instead of rendering exception templates
  config.action_dispatch.show_exceptions = false

  # Disable request forgery protection in test environment
  config.action_controller.allow_forgery_protection    = false

  # Tell Action Mailer not to deliver emails to the real world.
  # The :test delivery method accumulates sent emails in the
  # ActionMailer::Base.deliveries array.
  config.action_mailer.delivery_method = :test

  # Use SQL instead of Active Record's schema dumper when creating the test database.
  # This is necessary if your schema can't be completely dumped by the schema dumper,
  # like if you have constraints or database-specific column types
  # config.active_record.schema_format = :sql

  # Print deprecation notices to the stderr
  config.active_support.deprecation = :stderr

  # Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets
  config.assets.allow_debugging = true
end

And this is my spec_helper:

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'rubygems'
require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However, 
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  ENV["RAILS_ENV"] ||= 'test'
  unless defined?(Rails)
    require File.dirname(__FILE__) + "/../config/environment"
  end
  require 'rspec/rails'

  # Requires supporting files with custom matchers and macros, etc,
  # in ./support/ and its subdirectories.
  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

  Rspec.configure do |config|
    # == Mock Framework
    #
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
    #
    # config.mock_with :mocha
    # config.mock_with :flexmock
    # config.mock_with :rr
    config.mock_with :rspec

    config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, comment the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true

    ### Part of a Spork hack. See http://bit.ly/arY19y
    # Emulate initializer set_clear_dependencies_hook in 
    # railties/lib/rails/application/bootstrap.rb
    ActiveSupport::Dependencies.clear

    def test_sign_in(user)
      controller.sign_in(user)
    end
  end
end

Spork.each_run do
end

Thank you for your suggestions/answers!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你怎么敢 2024-12-12 20:18:44

该问题可以通过以下问题解决:

Cookie 确实不坚持在 Rails 3.1 上的 Rspec

这不是一个完美的方法,但它会起作用!

The problem can be resolved by following this question:

Cookies do not persist in Rspec on rails 3.1

Not a perfect way, but it'll work!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文