モデル内の属性の範囲をテストするための最も洗練された方法を見つけるのに問題があります。私のモデルは次のようになります。
class Entry < ActiveRecord::Base
attr_accessible :hours
validates :hours, presence: true,
:numericality => { :greater_than => 0, :less_than => 24 }
end
私のrspecテストは次のようになります。
require 'spec_helper'
describe Entry do
let(:entry) { FactoryGirl.create(:entry) }
subject { entry }
it { should respond_to(:hours) }
it { should validate_presence_of(:hours) }
it { should validate_numericality_of(:hours) }
it { should_not allow_value(-0.01).for(:hours) }
it { should_not allow_value(0).for(:hours) }
it { should_not allow_value(24).for(:hours) }
# is there a better way to test this range?
end
このテストは機能しますが、最小値と最大値をテストするためのより良い方法はありますか?私のやり方は不格好なようです。値の長さをテストするのは簡単なようですが、数値の値をテストする方法がわかりません。私はこのようなことを試しました:
it { should ensure_inclusion_of(:hours).in_range(0..24) }
しかし、それは包含エラーを予期しており、テストに合格することができません。たぶん私はそれを正しく構成していませんか?
以下に示すように、私は両方の境界で、上で、そして下でテストすることになりました。整数に制限しないので、小数点以下2桁までテストします。私のアプリの目的には、おそらくそれで「十分」だと思います。
it { should_not allow_value(-0.01).for(:hours) }
it { should_not allow_value(0).for(:hours) }
it { should allow_value(0.01).for(:hours) }
it { should allow_value(23.99).for(:hours) }
it { should_not allow_value(24).for(:hours) }
it { should_not allow_value(24.01).for(:hours) }