

参考書「rails5速習演習ガイド」に沿ってtaskleafというタスク管理アプリケーションを作成しているのですが、Rspec実行時にFailure/Errorエラーが出て解決法がわからないので質問させてください。

ルートディレクトリの Users/user/rails/taskleaf にて  
`$ bundle exec rspec spec/system/tasks_spec.rb` を実行後、以下のようなエラー文が出ます。

補足  
`('../config/environment', __dir__)` が書かれているfileは spec/rails_helper.rb です。

よろしくお願いします。

**環境**  
Rails 5.2.4  
Ruby 2.6.3

* * *

↓以下エラー全文です。

[code]

    An error occurred while loading ./spec/system/tasks_spec.rb.
    Failure/Error: require File.expand_path('../config/environment', __dir__)
    
    
    NameError:
      uninitialized constant BetterErrors
    # ./vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/active_support.rb:79:in `block in load_missing_constant'
    # ./vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/active_support.rb:8:in `without_bootsnap_cache'
    # ./vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/active_support.rb:79:in `rescue in load_missing_constant'
    # ./vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/active_support.rb:58:in `load_missing_constant'
    # ./config/initializers/better_errors.rb:1:in `<main>'
    # ./vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:54:in `load'
    # ./vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:54:in `load'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/engine.rb:663:in `block in load_config_initializer'
    # ./vendor/bundle/ruby/2.6.0/gems/activesupport-5.2.4/lib/active_support/notifications.rb:170:in `instrument'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/engine.rb:662:in `load_config_initializer'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/engine.rb:620:in `block (2 levels) in <class:Engine>'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/engine.rb:619:in `each'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/engine.rb:619:in `block in <class:Engine>'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/initializable.rb:32:in `instance_exec'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/initializable.rb:32:in `run'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/initializable.rb:61:in `block in run_initializers'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/initializable.rb:50:in `each'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/initializable.rb:50:in `tsort_each_child'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/initializable.rb:60:in `run_initializers'
    # ./vendor/bundle/ruby/2.6.0/gems/railties-5.2.4/lib/rails/application.rb:361:in `initialize!'
    # ./config/environment.rb:5:in `<top (required)>'
    # ./spec/rails_helper.rb:5:in `require'
    # ./spec/rails_helper.rb:5:in `<top (required)>'
    # ./spec/system/tasks_spec.rb:1:in `require'
    # ./spec/system/tasks_spec.rb:1:in `<top (required)>'
    # ------------------
    # --- Caused by: ---
    # NameError:
    #   uninitialized constant BetterErrors
    #   ./vendor/bundle/ruby/2.6.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/active_support.rb:60:in `block in load_missing_constant'
    No examples found.
    
    
    Finished in 0.00005 seconds (files took 4.78 seconds to load)
    0 examples, 0 failures, 1 error occurred outside of examples
    
[/code]

* * *

tasks_spec.rb

[code]

    require 'rails_helper'
    
    describe 'タスク管理機能', type: :system do
      let(:user_a) { FactoryBot.create(:user, name: 'ユーザーA', email: 'a@example.com') }
      let(:user_b) { FactoryBot.create(:user, name: 'ユーザーB', email: 'b@example.com') }
      let!(:task_a) { FactoryBot.create(:task, name: '最初のタスク', user: user_a) }
    
      before do
        visit login_path
        fill_in 'メールアドレス', with: login_user.email
        fill_in 'パスワード', with: login_user.password
        click_button 'ログインする'
      end
    
      shared_examples_for 'ユーザーAが作成したタスクが表示される' do
        it { expect(page).to have_content '最初のタスク' }
      end
    
      describe '一覧表示機能' do
        context 'ユーザーAがログインしているとき' do
          let(:login_user) { user_a }
    
          it_behaves_like 'ユーザーAが作成したタスクが表示される'
        end
    
        context 'ユーザーBがログインしているとき' do
          let(:login_user) { user_b }
    
          it 'ユーザーAが作成したタスクが表示されない' do
            expect(page).to have_no_content '最初のタスク'
          end
        end
      end
    
      describe '詳細表示機能' do
        context 'ユーザーAがログインしているとき' do
          let(:login_user) { user_a }
    
          before do
            visit task_path(task_a)
          end
    
          it_behaves_like 'ユーザーAが作成したタスクが表示される'
        end
      end
    
      describe '新規作成機能' do
        let(:login_user) { user_a }
        let(:task_name) { '新規作成のテストを書く' } # デフォルトとして設定
    
        before do
          visit new_task_path
          fill_in '名称', with: task_name
          click_button '登録する'
        end
    
        context '新規作成画面で名称を入力したとき' do
          it '正常に登録される' do
            expect(page).to have_selector '.alert-success', text: '新規作成のテストを書く'
          end
        end
    
        context '新規作成画面で名称を入力しなかったとき' do
          let(:task_name) { '' }
    
          it 'エラーとなる' do
            within '#error_explanation' do
              expect(page).to have_content '名称を入力してください'
            end
          end
        end
      end
    end
    
    
[/code]

* * *

rails_helper.rb

[code]

    # 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|
      # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
      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, remove the following line or assign false
      # instead of true.
      config.use_transactional_fixtures = true
    
      # RSpec Rails can automatically mix in different behaviours to your tests
      # based on their file location, for example enabling you to call `get` and
      # `post` in specs under `spec/controllers`.
      #
      # You can disable this behaviour by removing the line below, and instead
      # explicitly tag your specs with their type, e.g.:
      #
      #     RSpec.describe UsersController, :type => :controller do
      #       # ...
      #     end
      #
      # The different available types are documented in the features, such as in
      # https://relishapp.com/rspec/rspec-rails/docs
      config.infer_spec_type_from_file_location!
    
      # Filter lines from Rails gems in backtraces.
      config.filter_rails_from_backtrace!
      # arbitrary gems may also be filtered via:
      # config.filter_gems_from_backtrace("gem name")
    end
    
    
[/code]

* * *

spec_helper.rb

[code]

    # This file was generated by the `rails generate rspec:install` command. Conventionally, all
    # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
    # The generated `.rspec` file contains `--require spec_helper` which will cause
    # this file to always be loaded, without a need to explicitly require it in any
    # files.
    #
    # Given that it is always loaded, you are encouraged to keep this file as
    # light-weight as possible. Requiring heavyweight dependencies from this file
    # will add to the boot time of your test suite on EVERY test run, even for an
    # individual file that may not need all of that loaded. Instead, consider making
    # a separate helper file that requires the additional dependencies and performs
    # the additional setup, and require it from the spec files that actually need
    # it.
    #
    # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
    
    require 'capybara/rspec'
    
    RSpec.configure do |config|
      config.before(:each, type: :system) do
        driven_by :selenium_chrome_headless
      end
    
      # rspec-expectations config goes here. You can use an alternate
      # assertion/expectation library such as wrong or the stdlib/minitest
      # assertions if you prefer.
      config.expect_with :rspec do |expectations|
        # This option will default to `true` in RSpec 4. It makes the `description`
        # and `failure_message` of custom matchers include text for helper methods
        # defined using `chain`, e.g.:
        #     be_bigger_than(2).and_smaller_than(4).description
        #     # => "be bigger than 2 and smaller than 4"
        # ...rather than:
        #     # => "be bigger than 2"
        expectations.include_chain_clauses_in_custom_matcher_descriptions = true
      end
    
      # rspec-mocks config goes here. You can use an alternate test double
      # library (such as bogus or mocha) by changing the `mock_with` option here.
      config.mock_with :rspec do |mocks|
        # Prevents you from mocking or stubbing a method that does not exist on
        # a real object. This is generally recommended, and will default to
        # `true` in RSpec 4.
        mocks.verify_partial_doubles = true
      end
    
      # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
      # have no way to turn it off -- the option exists only for backwards
      # compatibility in RSpec 3). It causes shared context metadata to be
      # inherited by the metadata hash of host groups and examples, rather than
      # triggering implicit auto-inclusion in groups with matching metadata.
      config.shared_context_metadata_behavior = :apply_to_host_groups
    
    # The settings below are suggested to provide a good initial experience
    # with RSpec, but feel free to customize to your heart's content.
    =begin
      # This allows you to limit a spec run to individual examples or groups
      # you care about by tagging them with `:focus` metadata. When nothing
      # is tagged with `:focus`, all examples get run. RSpec also provides
      # aliases for `it`, `describe`, and `context` that include `:focus`
      # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
      config.filter_run_when_matching :focus
    
      # Allows RSpec to persist some state between runs in order to support
      # the `--only-failures` and `--next-failure` CLI options. We recommend
      # you configure your source control system to ignore this file.
      config.example_status_persistence_file_path = "spec/examples.txt"
    
      # Limits the available syntax to the non-monkey patched syntax that is
      # recommended. For more details, see:
      #   - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
      #   - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
      #   - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
      config.disable_monkey_patching!
    
      # Many RSpec users commonly either run the entire suite or an individual
      # file, and it's useful to allow more verbose output when running an
      # individual spec file.
      if config.files_to_run.one?
        # Use the documentation formatter for detailed output,
        # unless a formatter has already been configured
        # (e.g. via a command-line flag).
        config.default_formatter = "doc"
      end
    
      # Print the 10 slowest examples and example groups at the
      # end of the spec run, to help surface which specs are running
      # particularly slow.
      config.profile_examples = 10
    
      # Run specs in random order to surface order dependencies. If you find an
      # order dependency and want to debug it, you can fix the order by providing
      # the seed, which is printed after each run.
      #     --seed 1234
      config.order = :random
    
      # Seed global randomization in this process using the `--seed` CLI option.
      # Setting this allows you to use `--seed` to deterministically reproduce
      # test failures related to randomization by passing the same `--seed` value
      # as the one that triggered the failure.
      Kernel.srand config.seed
    =end
    end
    
    
[/code]

* * *

Gemfile

[code]

    source 'https://rubygems.org'
    git_source(:github) { |repo| "https://github.com/#{repo}.git" }
    
    ruby '2.6.3'
    
    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
    gem 'rails', '~> 5.2.3'
    # Use postgresql as the database for Active Record
    gem 'sqlite3'
    # Use Puma as the app server
    gem 'puma', '~> 3.11'
    # Use SCSS for stylesheets
    gem 'sass-rails', '~> 5.0'
    # Use Uglifier as compressor for JavaScript assets
    gem 'uglifier', '>= 1.3.0'
    # See https://github.com/rails/execjs#readme for more supported runtimes
    # gem 'mini_racer', platforms: :ruby
    
    # Use CoffeeScript for .coffee assets and views
    gem 'coffee-rails', '~> 4.2'
    # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
    gem 'turbolinks', '~> 5'
    # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
    gem 'jbuilder', '~> 2.5'
    # Use Redis adapter to run Action Cable in production
    # gem 'redis', '~> 4.0'
    #Use ActiveModel has_secure_password
    gem 'bcrypt', '>= 3.1.10'
    
    # Use ActiveStorage variant
    # gem 'mini_magick', '~> 4.8'
    
    # Use Capistrano for deployment
    # gem 'capistrano-rails', group: :development
    
    # Reduces boot times through caching; required in config/boot.rb
    gem 'bootsnap', '>= 1.1.0', require: false
    
    group :development, :test do
      # Call 'byebug' anywhere in the code to stop execution and get a debugger console
      gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
      gem 'factory_bot_rails', '~> 5.1', '>= 5.1.1'
    end
    
    group :development do
      # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
      gem 'web-console', '>= 3.3.0'
      gem 'listen', '>= 3.0.5', '< 3.2'
      # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
      gem 'spring'
      gem 'spring-watcher-listen', '~> 2.0.0'
    
      gem 'better_errors'
      gem 'binding_of_caller'
      gem 'pry-rails'
    
    end
    
    group :test do
      # Adds support for Capybara system testing and selenium driver
      gem 'capybara', '>= 2.15'
      gem 'selenium-webdriver'
      # Easy installation and use of chromedriver to run system tests with Chrome
      gem 'webdrivers', '~> 3.0'
      gem 'rspec-rails', '~> 3.9'
      gem 'factory_bot_rails', '~> 5.1', '>= 5.1.1'
    end
    
    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
    gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
    
    gem 'slim-rails'
    gem 'html2slim'
    
    gem 'bootstrap'
    gem 'nokogiri', '~> 1.10', '>= 1.10.5'
    gem 'rails_autolink'
    
    gem 'pry-byebug', group: :development
    gem 'pry-doc'
    
    
[/code]

* * *

__dir___spec.rb

[code]

    require_relative '../../spec_helper'
    
    describe "Kernel#__dir__" do
      it "returns the real name of the directory containing the currently-executing file" do
        __dir__.should == File.realpath(File.dirname(__FILE__))
      end
    
      context "when used in eval with a given filename" do
        it "returns File.dirname(filename)" do
          eval("__dir__", nil, "foo.rb").should == "."
          eval("__dir__", nil, "foo/bar.rb").should == "foo"
        end
      end
    
      context "when used in eval with top level binding" do
        it "returns the real name of the directory containing the currently-executing file" do
          eval("__dir__", binding).should == File.realpath(File.dirname(__FILE__))
        end
      end
    end
    
    
[/code]


CC BY-SA 4.0
2019-12-09T23:03:42.520
61284
2022-10-14T06:03:25.113
2019-12-10T00:17:16.223
3060
36775
question
ruby-on-rails rspec
rails5でRspec実行時にFailure/Errorエラーが出ます


`./config/initializers/better_errors.rb`  
が未定義のBetterErrorsを参照しているようです。  
[BetterErrors](https://github.com/BetterErrors/better_errors/wiki/Link-to-
your-editor)に記載のとおり、`if defined?(BetterErrors)`で定義済みかチェックする必要があります。


CC BY-SA 4.0
2019-12-16T02:38:49.610
61468
2019-12-16T02:38:49.610
28970
61284
answer


`better_errors`
gemのinitializerファイルをロードしようとして`BetterErrors`クラスが見つからない。という流れのエラーですので、`./config/initializers/better_errors.rb`を削除して実行してみるとどうでしょう。

デフォルトではこのファイルは作成されないようです。書籍のなかで追加されたとかですか？  
<https://github.com/BetterErrors/better_errors#set-maximum-variable-size-for-
inspector>

あとは、`Gemfile`での定義を確認してみるとかでしょうか。

こうなっていると、`development`、`test`の環境で有効になりますが、

[code]

    group :development, :test do
      gem "better_errors"
    end
    
[/code]

このようにすると、`development`のみで有効にできるので、rspec実行時（test環境）では読み込まれないかと。

[code]

    group :development
      gem "better_errors"
    end
    
[/code]


CC BY-SA 4.0
2020-10-05T01:20:09.000
70913
2020-10-05T01:20:09.000
32317
61284
answer