rails factory rspec测试失败,因为" only_integer"模型验证

时间:2017-07-12 03:32:38

标签: ruby-on-rails activerecord rspec rails-activerecord factory-bot

我的模型有一个工厂'价格'但是当我将价格验证作为only_integer时,所有的rspec测试都开始失败。我尝试使用rspec验证工厂时得到的错误是" Price必须是整数"

这是我的模特档案:

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

这是我工厂的价格:

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

这是我的迁移文件:

    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

编辑:添加rspec测试和错误:

控制器rspec测试:

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

我得到的错误:

 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)>'

我是rails的新手所以请原谅我,如果我没有提供足够的信息或做一些非常愚蠢的事情。

1 个答案:

答案 0 :(得分:0)

我不知道为什么或如何运作,但我将出厂价格值转换为字符串并且所有测试都通过了。

我很想知道为什么会发生这种情况。

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