如何在OpenStruct上存根方法?

时间:2017-03-10 19:54:13

标签: ruby-on-rails-4 rspec

我有一个rspec测试,它执行以下操作:

  enrollment_hash = {
      checked_dependents: []
  }
  enrollment = OpenStruct.new enrollment_hash

  org_plan_response.new(enrollment)

在org_plan_response中我有:

@enrollment.requires_termination_reason?(x, y)

我想在测试中删除requires_termination_reason,但无法弄明白。

我试过了:enrollment.stub(:requires_termination_reason?).with('x', 'y').and_return { false }

但得到:

  

NoMethodError:#<未定义方法`stub' OpenStruct checked_dependents = []>

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

require 'ostruct'

describe "" do
  specify "" do
    enrollment = OpenStruct.new(checked_dependents: [])

    allow(enrollment).to receive(:requires_termination_reason?).with('x', 'y').and_return(false)

    expect(enrollment.requires_termination_reason?('x', 'y')).to be false
  end
end

以上代码适合我。请注意确保带有存根的enrollment对象与测试中使用的对象相同。