无法从Rspec spec_helper.rb文件

时间:2016-08-29 06:41:12

标签: ruby-on-rails rspec factory-bot

我正在尝试在运行任何测试之前加载一些种子数据。我正在做以下事情:

spec_helper.rb

# 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.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|

      config.before(:suite) do
        Rails.application.load_seed # loading seeds
      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

config.before(:each) { ActionMailer::Base.deliveries.clear }   

# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
  # These two settings work together to allow 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.
  config.filter_run :focus
  config.run_all_when_everything_filtered = true

  # 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

我收到如下错误:

spec/factories/employees.rb:25:in `block (2 levels) in <top (required)>': undefined method `id' for nil:NilClass (NoMethodError)

employees.rb工厂

require 'faker'

FactoryGirl.define do
  factory :employee do
    first_name { Faker::Name.first_name}
    last_name { Faker::Name.last_name}
    sequence(:email) { |n| "peterjohnson#{n}@example.com" }
    mobile 66816927867
    bio "MyText"
    address { Faker::Address.street_address}
    province_state { Faker::Address.state}
    country { Faker::Address.country}
    postal_code { Faker::Address.postcode}
    status :active
    bachelor_degree "B.Sc"
    password Faker::Internet.password(8)
    sequence(:paypal_email) { |n| "paypal_peterJohnson#{n}@example.com" }
    sequence(:skype_id) {|n| "peterjohnson_skype#{n}" }
    os :mac
    role_ids [Role.first.id]

    trait :proofreader do
        after(:create) {|employee| employee.add_role(:proofreader)}
    end

    trait :admin do
        after(:create) {|employee| employee.add_role(:admin)}
    end

    trait :super_admin do
        after(:create) {|employee| employee.add_role(:super_admin)}
    end
  end
end

seeds.rb

# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
#   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
#   Mayor.create(name: 'Emanuel', city: cities.first)

#Seeding the Role table
#
p "Removing existing #{Role.all.count} roles"
Role.destroy_all
p "Creating 3 roles"
[:proofreader, :admin, :super_admin].each do |role|
  Role.create( name: role )
end
p "Should have created 3 Roles, roles created: #{Role.all.count}"

#Seed the Employee table

#create super_admin employee
p "Removing existing #{Employee.all.count} employees"
Employee.destroy_all
p "Creating one employee"

super_admin = Employee.create(first_name: "Mitchell", last_name: "Gould", email: "mitchell@provenword.com", paypal_email: "go_mitchell@yayoo.ca", skype_id: "chellgouda", mobile: 66816927867, bachelor_degree: "Science", password: "chokta400",postal_code: "50100",address: "211/195 Soi 27, Sriwalee Klong Chun, T. Mae Hia, A. Muang", province_state: "Chiangmai", country: "Thailand", status: "active", os: "mac", role_ids: [Role.last.id])
super_admin.add_role(:proofreader)


p "Should have created #{Employee.all.count} employee with name #{Employee.first.first_name}."

为什么在加载种子数据之前工厂正在运行?

2 个答案:

答案 0 :(得分:0)

您可能在db/seeds.rb

中使用FactoryGirl

答案 1 :(得分:0)

而不是spec_helper文件,将其添加到rails帮助文件中。

require 'rspec/rails'

我把它放在

之后的顶部附近

@MessageMapping("static.queue") public void receiveMessage(Payload payload) { // ... }

但是,根据您的种子数据和您正在使用的宝石(即数据库清理程序),您需要进行修改,以便在适当之前不会删除种子数据。