ruby-on-rails - Rspec Rails - 使用 :find_each 进行迭代的 stub 事件记录关系

标签 ruby-on-rails rspec-rails

我正在尝试测试特定属性 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/

相关文章:

ruby-on-rails - 事件记录范围的可互换性和顺序

ruby-on-rails - rails 中图像和 js/css 文件后的问号。为什么?

ruby-on-rails - Rails 7 - render_to_string - MissingTemplate

ruby-on-rails - 预期 true 会回应 true 吗?

ruby-on-rails - Rails 没有使用正确版本的 Ruby

ruby-on-rails - 不推荐在模板名称中传递模板处理程序是什么意思。意思是?

ruby-on-rails - 为什么我的 rspec-rails 生成的规范由于路由异常而失败?

delegation - Rails/Rspec - 为委托(delegate)方法编写规范(allow_nil 选项)

ruby-on-rails - 为什么 before_action :authorize fail with 'wrong number of arguments' ?

ruby-on-rails - 如何访问 Devise Controller ?