【问题标题】:FactoryGirl can't access my modelsFactoryGirl 无法访问我的模型
【发布时间】:2017-01-12 15:43:08
【问题描述】:

问题

当我尝试运行bundle exec rspec 时,我总是收到此错误:

Failure/Error: before { @user = FactoryGirl.build(:user) }
     
     NameError:
       uninitialized constant User

为什么 FactoryGirl 看不到我的模型?以下是我的一些文件,供参考:

文件

我的工厂:

# spec/factories/users.rb
FactoryGirl.define do
  factory :user, class: User do
    email { FFaker::Internet.email }
    password "12345678"
    password_confirmation "12345678"
  end
end

我的模特:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :jogs
end

我的规格:

require 'spec_helper'

describe 'User' do
  before { @user = FactoryGirl.build(:user) }

  subject { @user }

  it { is_expected.to respond_to(:email) }
  it { is_expected.to respond_to(:password) }
  it { is_expected.to respond_to(:password_confirmation) }

  it { is_expected.to be_valid }
end

我的 spec_helper(没有所有 cmets):

require 'factory_girl_rails'
FactoryGirl.find_definitions

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods

  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.shared_context_metadata_behavior = :apply_to_host_groups

我的 rails_helper(没有 cmets):

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|


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

  config.use_transactional_fixtures = true

  config.infer_spec_type_from_file_location!

  config.filter_rails_from_backtrace!
end

【问题讨论】:

  • 另外我相信,你可以跳过工厂定义中的class: User 部分,因为它会按照惯例选择类。
  • 是的,我稍后把它放上,以防万一它会有所帮助,但它不是必需的。

标签: ruby-on-rails rspec ruby-on-rails-5


【解决方案1】:

您的规范中应该有 require 'rails_helper' 而不是 require 'spec_helper'

【讨论】:

  • 非常感谢,你改变了我的生活。我保证从现在开始成为素食主义者。问题是我是从 spec_helperrails_helper 两个不同的东西之前制作的过时教程中复制的。
  • 对不起,我不是打算让人们成为素食主义者)。升级 rspec 时,我也遇到了过时代码的类似问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2012-04-07
  • 1970-01-01
  • 2016-03-22
相关资源
最近更新 更多