如何在Rails测试中存根设置对象属性的方法?

时间:2017-05-04 14:56:08

标签: ruby-on-rails rspec mocha

我正构建一个Rails spec测试,它有一个名为temp_coverage的Struct,如下所示:

  temp_coverage = Struct.new(:paydays) do
    def calculate_costs
      50
    end
  end

在我的规范中,我使用temp_coverage调用一个方法,但由于我正在测试的代码执行以下操作,我收到错误:

temp_coverage.req_subscriber_election_amount = subscriber_election_amount

我收到了一个错误:

  

NoMethodError:未定义的方法`req_subscriber_election_amount =' for< struct paydays = 12>

如何在规范中结构化某个属性的设置?

2 个答案:

答案 0 :(得分:1)

你在寻找这样的东西吗?

temp_coverage = double('temp_coverage', paydays: nil)

allow(temp_coverage).to receive(:calculate_costs).and_return(50)
allow(temp_coverage).to receive(:req_subscriber_election_amount=) do |argument|
  temp_coverage.instance_variable_set(:@req_subscriber_election_amount, argument)
end

# Example:
temp_coverage.req_subscriber_election_amount = 123
puts temp_coverage.instance_variable_get(:@req_subscriber_election_amount)
# => 123
puts temp_coverage.paydays
# => nil
puts temp_coverage.calculate_costs
# => 50

答案 1 :(得分:0)

我通过使用命名的Struct找到了一种方法。所以,一旦我命名我的结构:

 temp_coverage = Struct.new('CoverageClass', :paydays) do
    def calculate_costs
      50
    end
  end

然后我可以执行以下操作:

Struct::CoverageClass.any_instance.stubs(:req_subscriber_election_amount).returns(25)