In RSpec - how can I test if one attribute is less (or more) than another

Nikita Hismatov picture Nikita Hismatov · Feb 22, 2013 · Viewed 13.8k times · Source

In my app I want to have a Car model.

It will have two fields among others: date_from and date_till (to specify a period of time someone was using it).

And I want the model to validate that date_from should be less or equal than date_till.

My model_spec.rb draft looks like this:

require 'spec_helper'

describe Car do
  it {should validate_presence_of(:model)}
  it {should validate_presence_of(:made)}

  it "should have date_till only if it has date_from"
  its "date_till should be >= date_from"
end

Obviously, I can just write a "long" test where I will try to set date_till to be greater than date_from - and the model just should be invalid. But maybe there are some elegant ways to do it?

So, how can I (using RSpec matchers) validate that one field is not greater than another?

upd: I looked at @itsnikolay's answer and coded it like that:

it "should not allow date_till less than date_from" do
  subject.date_from = Date.today
  subject.date_till = Date.today - 1.day

  subject.valid?.should be_false
end

Had to do it without matchers. Well, not a tragedy :)

Answer

Rian Rainey picture Rian Rainey · May 28, 2014

It is generally recommended to use expect, not should.

For instance:

  expect(@car.date_from).to be <= @car.date_till

Resources: - BetterSpecs examples - Rspec Docs