How to use rspec to test ActiveRecord model scopes and queries

64 views Asked by At

I am trying to write rspec-rails tests on my ActiveRecord Flight object scopes (e.g. #around_date). Here's one test I've written:

  let(:flight) { create(:flight) } 
  date = DateTime.new(year=2023, month=12, day=25)

  it 'selects within default date range' do
    flights = Flight.around_date(date.to_s).to_a
    expect flights.to include(flight)
  end

This is supposed to test that the #around_date scope will return the Flight object created with let. (The factory creates them with the date 12-25-2023).

Here is the code for the #around_date scope within the Flight model:

scope :around_date, ->(date_string, day_interval = 1) {
    if date_string.present?
      date = Date.parse(date_string)

      lower_date = date - day_interval.days
      upper_date = date + day_interval.days
      where(start_datetime: (lower_date..upper_date))
    end
  }

When I run the test I get the following error message:

 Failure/Error: expect flights.to include(flight)
 
 NoMethodError:
   undefined method `>=' for #<RSpec::Matchers::BuiltIn::ContainExactly:0x00007fe400279098 @expected=[#<Flight id: 1, departure_airport_id: 2, arrival_airport_id: 1, start_datetime: "2023-12-25 00:00:00.000000000 +0000", duration_minutes: 30, created_at: "2023-12-02 16:51:32.363329000 +0000", updated_at: "2023-12-02 16:51:32.363329000 +0000">]>
 # ./spec/models/flight_spec.rb:11:in `block (4 levels) in <main>'

I'm lost as to what this error message means as there is no case of >= anywhere in the relevant code.

Any ideas as to what this error message could mean would be greatly appreciated!

2

There are 2 answers

0
user23037192 On

Your test should be:

let(:flight) { create(:flight) }  
date = DateTime.new(year=2023, month=12, day=25)

it 'selects within default date range' do   
  flights = Flight.around_date(date.to_s).to_a   
  expect(flights).to include(flight) 
end
0
imsachinshah0 On

expect now accepts the block so pass flights within the block.

it 'selects within default date range' do
  flights = Flight.around_date(date.to_s).to_a
  expect {flights}.to include(flight)
end