ruby-on-rails 如何使用rspec测试ActiveRecord模型范围和查询

tag5nh1u  于 5个月前  发布在  Ruby
关注(0)|答案(2)|浏览(62)

我尝试在我的ActiveRecord Flight对象作用域(例如#around_date)上编写rspec-rails测试。下面是我编写的一个测试:

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

字符串
这是为了测试#around_date作用域是否会返回用let创建的Flight对象。(工厂用日期12-25-2023创建它们)。
下面是Flight模型中#around_date作用域的代码:

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
  }


当我运行测试时,我得到以下错误消息:

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>'


我不知道这个错误消息是什么意思,因为在相关代码中没有>=的情况。
任何想法,以什么这个错误消息可能意味着将不胜感激!

gev0vcfq

gev0vcfq1#

你的测试应该是:

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

字符串

bsxbgnwa

bsxbgnwa2#

expect现在接受这个块,所以在块内传递flights

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

字符串

相关问题