Note that there are some explanatory texts on larger screens.

plurals
  1. POrspec test model for minimum and maximum values
    primarykey
    data
    text
    <p>I'm having some trouble finding the most elegant way to test the range of an attribute in my model. My model looks like:</p> <pre><code>class Entry &lt; ActiveRecord::Base attr_accessible :hours validates :hours, presence: true, :numericality =&gt; { :greater_than =&gt; 0, :less_than =&gt; 24 } end </code></pre> <p>My rspec tests look like:</p> <pre><code>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 </code></pre> <p>This test works, but is there a better way to test the minimum and maximum values? My way seems clunky. It seems easy to test the length of a value, but I'm not seeing how to test the values of a number. I've tried something like this:</p> <pre><code>it { should ensure_inclusion_of(:hours).in_range(0..24) } </code></pre> <p>But that is expecting an inclusion error, and I can't get my test to pass. Maybe I'm not configuring it correctly?</p> <hr> <p>I ended up testing at, above, and below both of my boundaries as suggested below. Because I don't restrict to integers I testing to two decimal places. I think that's probably "good enough" for the purposes of my app.</p> <pre><code>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) } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload