factorybot does not work

Asked 2 years ago, Updated 2 years ago, 89 views

Currently using rspec to study test code.
So I am using factory_bot, but I get an error in the build.
KeyError: Factory not registered:
Here is the error statement.

https://masawada.hatenablog.jp/entry/2018/01/06/012845
I changed the description by referring to this article, but it has not been resolved.
Please teach me.

Rails 5.2.4.1
ruby 2.5.1

spec/modles/comment_spec.rb

require 'rails_helper'

describe Comment do
  describe'#create'do

    it "Nickname cannot be registered empty" do
      comment=build(:comment,nickname:"")
      comment.valid?
      expect(comment.errors[:nickname]).to include("")
    end

  end
end

spec/factories/comments.rb

FactoryBot.definedo

  factory —Comment do
    nickname {"Tanaka"}
    text {"text"}
  end

end

Terminal

Comment
  #create
    Nickname cannot be registered empty (FAILED-1)

Failures:

  1) Comment#create nickname cannot be registered empty
     Failure/Error: comment=build(:comment,nickname:"")

     KeyError:
       Factory not registered: "comment"
     # ./spec/models/comment_spec.rb:7:in`block(3 levels) in<top(required)>'
     # ------------------
     # --- Caused by :-
     # KeyError:
     #   key not found: "comment"
     #   ./spec/models/comment_spec.rb:7:in`block(3 levels) in<top(required)>'

Finished in 0.04478 seconds (files book 1.45 seconds to load)
1 example, 1 failure

Failed examples:

rspec./spec/models/comment_spec.rb: 6 #Comment #create Nickname Cannot Register Empty

gemfile

source 'https://rubygems.org'
git_source(:github){|repo|"https://github.com/#{repo}.git"}

ruby '2.5.1'

# Bundle edge Rails installed: gem 'rails', github: 'rails/rails'
gem 'rails', '~>5.2.3'
# Use mysql as the database for Active Record
gem 'mysql2', '>=0.4.4', '<0.6.0'
# 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 assemblies
gem 'uglifer', '>=1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtime
# gem'mini_racer', platforms::ruby

# Use CoffeeScript for.coffee assemblies 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.7'

# Use ActiveStorage variant
# gem'mini_magic', '~>4.8'

# Use Capistrano for deployment
# gem 'capistrano-rails', group::development

# Reduce 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'rspec-rails'
  gem 'factory_bot_rails'
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's spring-watcher-listen', '~>2.0.0'
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'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem'tzinfo-data', platforms: [:mingw,:mswin,:x64_mingw,:jruby]
gem "haml-rails", ">=1.0", '<=2.0.1'
gem "pry-rails"
gem 'devise'
gem'carrierwave'
gem'mini_magic'
gem "font-awesome-sass"
gem 'jquery-rails'
gem'kaminari'

rails_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 requirements below this line.Rails is not loaded until this point!

# Requirements supporting ruby files with custom matches 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 specifics, causing the specific to be
# runtime.It is recommended that you do not name files matching this globe 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 convention purpos. It is 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')] .sort.each {|f|require f}

# Checks for pending migrations and apps 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
  exit1
end
RSpec.configure do | config |
  config.include FactoryBot::Syntax::Methods

  config.before(:all)do
    FactoryBot.reload
  end
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixes
  config.fixure_path="#{:Rails.root}/spec/fixes"
  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples with a transaction, remove the following line or assign false
  # installed of true.
  config.use_transactional_fixes=true

  # You can comment this line to turn off ActiveRecord support entry.
  # config.use_active_record=false

  # RSpec Rails can automatically mix in different behaviors to your tests
  # based on their file location, for example enabling you to call `get` and
  # `post`inspecs under`spec/controllers`.
  #
  # You can disable this behavior by removing the line below, and install
  # explicitly tag your specifications 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 be filtered via:
  # config.filter_gems_from_backtrace("gem name")

end

spec_helper.rb

#This file was generated by the `rails generate rspec:install`command.Conventionally, all
# specs live under a `spec` directory, which RSspec addresses to the `$LOAD_PATH`.
# The generated`.rspec`file contains`--require spec_helper`which will cause
# This file to always be loaded, without need to explicitly require it in any
# files.
#
# Given that is always loaded, you are encountered 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, consumer making
# separate helper file that require the additional dependencies and performances
# the additional setup, and require it from the spec files that actively need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do | config |
  # 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 RSpec4. It makes the `description`
    # and `failure_message` of custom matches 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
    # real object.This is generally recommended, and will default to
    # `true` in RSpec4.
    mocks.verify_partial_doubles=true
  end

  # This option will default to `: apply_to_host_groups` in RSpec4(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
  # inherit by the metadata hash of host groups and examples, again 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 offers
  # aliases for `it`, `describe`, and `context` that include`: focus`
  # metadata: `fit', `fdescribe` and `fcontext', responsively.
  config.filter_run_when_matching:focus

  # Allows RSspec 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 common 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 specifics in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by provisioning
  # The seed, which is printed after each run.
  #     --seed1234
  config.order= —Random

  # Seed global randomization in this process using the `--seed` CLI option.
  # Setting this allows you to use ` -- seed ` to determinely reproduce
  # test failures related to randomization by passing the same ` --seed `value
  # as the one that triggered the failure.
  Kernel.sland config.seed
=end
end

ruby-on-rails ruby rspec test

2022-09-30 19:43

1 Answers

You can think of a problem with spring. Stop spring stop and try again.


2022-09-30 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.