【问题标题】:undefined method `create' in Rails RSpecRails RSpec中未定义的方法“create”
【发布时间】:2016-02-23 02:29:12
【问题描述】:

我已安装 FactoryBot 并尝试将其与 RSpec 一起使用。

scenario 'User signs in' do
  create :user, email: 'test@example.com', password: 'testpassword'
  visit '/users/sign_in'

  fill_in 'Email', with: 'test@example.com'
  fill_in 'Password', with: 'testpassword'
end

我收到以下错误。

Failure/Error: create :user, email: 'test@example.com', password: 'testpassword'
 NoMethodError:
   undefined method `create' for #<RSpec::ExampleGroups::UserSignIn:0x007fe6324816b8>

【问题讨论】:

  • 试试FactoryGirl.create

标签: rspec factory-bot rspec-rails


【解决方案1】:

在我的情况下,我在rails_helper.rb 中缺少config.include FactoryGirl::Syntax::Methods

【讨论】:

    【解决方案2】:

    我们可以在factory_bot's documentation找到解决方案:

    1) 创建文件/spec/support/factory_bot.rb

    RSpec.configure do |config|
      config.include FactoryBot::Syntax::Methods
    end
    

    2) 编辑 /spec/rails_helper.rb 以加载 support 目录中的所有文件:

    Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
    

    【讨论】:

      【解决方案3】:

      转到 /spec/rails_helper.rb 并搜索 Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f|要求 f } 并取消注释

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多