0
votes

I have a factory for my model 'price' but all rspec tests start failing when I put the validation for price as only_integer. The error i get when i try to validate factory using rspec is "Price must be an integer"

Here's my model file:

class Price < ApplicationRecord
   belongs_to :expertise
   validates :price,
      :presence => true,
      :numericality => { only_integer: true }
end

Here's my factory for price:

    FactoryGirl.define do
      factory :price do
        association :expertise, factory: :expertise, strategy: :create
        price 10
        # price Faker::Number.between(1,1000).to_i
      end
    end

Here's my migration file:

    class CreatePrices < ActiveRecord::Migration[5.0]
       def change
         create_table :prices do |t|
         t.integer :expertise_id
         t.integer :price
         t.timestamps
       end
     add_index :prices, [:expertise_id], unique: true
     end
   end

EDIT: Adding rspec test and error:

The controller rspec test:

require 'rails_helper'

RSpec.describe PricesController, type: :controller do

  let(:price) {FactoryGirl.create(:price)}

  describe "GET show" do
    it "renders :show template" do
      get :show, params: { id: price.id }
      expect(response).to render_template(:show)
    end
  end
end

The error I get:

 1) PricesController GET show renders :show template
    Failure/Error: let(:price) {FactoryGirl.create(:price)}

 ActiveRecord::RecordInvalid:
   Validation failed: Price must be an integer
 # ./spec/controllers/prices_sample_controller.rb:7:in `block (2 levels) in <top (required)>'
 # ./spec/controllers/prices_sample_controller.rb:11:in `block (3 levels) in <top (required)>'

I am new to rails so please excuse me if I am not providing enough information or doing something really stupid.

1
please share the rspec and and error backtraceNimish Gupta
Idk, but sometimes factorygirl generate float instead integer.buncis
Try this one: price { Faker::Number.between(1,1000).to_i }nattfodd
@NimishGupta I posted my rspec test and error. Please take a lookSam
@nattfodd Tried that too. Didn't work!Sam

1 Answers

0
votes

I am not sure why or how this works, but i converted my factory price value to string and all tests pass.

I am really curious to know why this behavior is happening.

FactoryGirl.define do
  factory :price do
    association :expertise, factory: :expertise, strategy: :create
    # price Faker::Number.between(1,1000).to_i
    price Faker::Number.between(1,1000).to_s
  end
end