93

我第二次做 Rails 教程。当我输入这个

rails generate integration_test static_pages

我得到spec/rails_helper.rbspec/spec_helper.rb而不仅仅是spec/spec_helper.rb

现在当我运行我的测试时,它们比我上次做的时候更长(更“冗长”)并且更慢。我想知道这两个文件之间的区别是什么,以及我是否做错了什么。rails_helper.rb另外,有没有办法在不搞乱一切的情况下摆脱文件?

4

2 回答 2

137

rspec-rails 3 生成spec_helper.rbrails_helper.rb. spec_helper.rb适用于不依赖于 Rails 的规范(例如 lib 目录中的类的规范)。rails_helper.rb适用于依赖于 Rails 的规范(在 Rails 项目中,大部分或全部)。rails_helper.rb需要spec_helper.rb. 所以不,不要摆脱rails_helper.rb; spec_helper.rb在您的规格中要求它(而不是)。

如果您希望您的不依赖于 Rails 的规范强制它们不依赖于 Rails,并在您自己运行它们时尽可能快地运行,您可以要求spec_helper.rb而不是rails_helper.rb那些。但是-r rails_helper在你的.rspec而不是在每个规范文件中都需要一个助手或另一个助手非常方便,所以这肯定是一种流行的方法。

如果您使用的是 spring 预加载器,则每个类只需要加载一次,即使您只运行一个需要的规范,spring 也会急切地加载类spec_helper,因此仅spec_helper在某些文件中 require 没有太大的价值。

资料来源:https ://www.relishapp.com/rspec/rspec-rails/docs/upgrade#default-helper-files

于 2014-06-10T16:04:53.277 回答
1

您始终可以将所有配置组合到 spec_helper 中,并且只需要在 rails helper 文件中使用 spec helper。

这绝不是“理想的”,因为归根结底,您正在手动执行此“重构”,但如果它真的让您感到困扰。只知道这完全取决于您如何构建Rspec.configure

#rails_helper.rb

require 'spec_helper'

#EMPTY FILE

并且只需引入所有特定于轨道的设置

# spec_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'

require File.expand_path('../config/environment', __dir__)

# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!

# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }

# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
RSpec.configure do |config|

... all our config.whatever_your_heart_desires
于 2019-12-23T16:58:26.633 回答