为 RSpec rails 5 创建的未定义方法

undefined method create for RSpec rails 5

This 可能重复,但它对我不起作用。 请让我知道我错过了什么。

配置详情:

#Gemfile
gem 'factory_bot_rails' # 4.8.2

#spec/rails_helper.rb
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
  #other config
end

spec/factories/otps.rb

FactoryBot.define do
  factory :otp do
    phone { Faker::Number.number(10) }
    expiry { Time.now + Otp::Constants::EXPIRY_DURATION }
    password { Faker::Number.number(4) }
  end
end

spec/requests/authentication_controller_spec.rb

require 'spec_helper'
RSpec.describe "Authentication", :type => :request do
  describe "when invalid OTP is passed" do
    it "should return bad request" do
      otp = create(:otp) # ===> Throws error
    end
  end
end

更改您的规格以包括正确的助手:

require 'rails_helper'

RSpec.describe "Authentication", :type => :request do
  describe "when invalid OTP is passed" do
    it "should return bad request" do
      otp = create(:otp)
    end
  end
end

如果您使用 .rspec 文件,您也可以跳过该行,其中包含类似以下内容:

 --color
 --format progress
 --order random
 --require rails_helper