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 :)
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
只需使用<=
date_from.should be <= date_till
@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
或者用新语法
expect(date_from).to be <= date_till
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.