Rspec Rails - 存根 Active Record 关系以迭代使用 :find_each

Rspec Rails - Stub Active Record Relation to iterate using :find_each

我正在尝试测试特定属性 some_field 是否被分配了正确的值。由于速度问题,我目前没有将记录保存在数据库中,所以我只需要通过存根的方法。

这是一个示例方法:

  class Teacher < ApplicationRecord 
    has_many :students

    def my_method
      ...
      teacher.students.find_each do |s|
        s.some_field[:foo] = 'bar'
        s.save
      end
    end
  end

这是失败的测试规范:find_each 仅适用于 ActiveRecord 关系:

it 'assigns a correct value in some_field attribute' do
  allow(teacher).to receive(:students).and_return([student1])
  allow(student1).to receive(:save)

  teacher.my_method
  expect(student1.some_field).to eq({ foo: 'bar' })
end

错误:

NoMethodError:
   undefined method `find_each' for #<Array:0x00007fa08a94b308>

我想知道是否有无需在数据库中坚持的方法?

我们将不胜感激。

同时模拟 find_each 和 return 正则。

let(:teacher) { double }
let(:students_mock) { double }
let(:student1) { double }

it do
  expect(teacher).to receive(:students).and_return(students_mock)
  expect(students_mock).to receive(:find_each) { |&block| [student1].each(&block) }
  expect(student1).to receive(:save)

  teacher.students.find_each(&:save)
end