我正在尝试测试特定属性 some_field
是否被分配了正确的值。由于速度问题,我目前没有将记录保留在数据库上,因此我需要一种仅通过 stub 的方法。
这是一个示例方法:
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 并返回常规的each。
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
关于ruby-on-rails - Rspec Rails - 使用 :find_each 进行迭代的 stub 事件记录关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63050273/