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

5

47

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 "does 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 :)

Albata answered 22/2, 2013 at 9:18 Comment(0)
S
120

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

Sextet answered 28/5, 2014 at 12:45 Comment(1)
and if you are into one-liners: it { is_expected.to be <= @car.date_till }Damicke
E
14

Just use <=

date_from.should be <= date_till
Engelbert answered 22/2, 2013 at 9:19 Comment(1)
if they both initialized as nil? test will pass, but does it cover all the behavior?Albata
F
7

Or in new syntax

expect(date_from).to be <= date_till
Faithless answered 7/3, 2017 at 16:33 Comment(0)
R
6
@car = Car.create \
  name:      'Buggy',
  date_from: Date.today + 1.day,
  date_till: Date.today + 2.day

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

More details: RSpec Comparison matchers

Ramunni answered 22/2, 2013 at 10:34 Comment(0)
O
-1

expect(value1 < value2).to be_truthy should do it

Oysterman answered 10/3, 2023 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.