Search code examples
rspecruby-on-rails-5factory-botrspec-rails

undefined method create for RSpec rails 5


This may a possible duplicate however it did not work for me. Please let me know what did I miss.

Config details:

#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

Solution

  • Change your spec to include the right helper:

    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
    

    You can also skip that line, if you use a .rspec file, which would include something like:

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