In RSpec - how can I test if one attribute is less (or more) than another
Solution 1
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
Solution 2
Just use <=
date_from.should be <= date_till
Solution 3
Or in new syntax
expect(date_from).to be <= date_till
Solution 4
@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
Nikita Hismatov
I've been coding in web (php, python, nodejs) for 7 years. And I was learning functional programming - just for fun, not meaning to go deeper. But eventually I realized that it's the thing I want to do. And now I work as a freelance haskell programmer.
Updated on July 31, 2022Comments
-
Nikita Hismatov almost 2 years
In my app I want to have a
Car
model.It will have two fields among others:
date_from
anddate_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 :)
-
Nikita Hismatov about 11 yearsif they both initialized as nil? test will pass, but does it cover all the behavior?
-
Salomanuel over 3 yearsand if you are into one-liners:
it { is_expected.to be <= @car.date_till }