简体   繁体   English

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

[英]How to stub a method that sets an object attribute in a Rails test?

I'm building a Rails spec test that has a Struct called temp_coverage, like this: 我正在构建一个名为temp_coverage的Struct的Rails规范测试,如下所示:

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

And in my spec, I call a method using the temp_coverage, but I'm getting an error since the code I am testing is doing the following: 在我的规范中,我使用temp_coverage调用了一个方法,但是由于要测试的代码正在执行以下操作,因此出现错误:

temp_coverage.req_subscriber_election_amount = subscriber_election_amount

And I am getting an error: 我收到一个错误:

NoMethodError: undefined method `req_subscriber_election_amount=' for < struct paydays=12 > NoMethodError:未定义的方法'req_subscriber_election_amount ='for <结构发薪日= 12>

How can I stub out the setting of an attribute on a struct in my spec? 如何在规范中对结构的属性设置进行存根处理?

Is something like this you're looking for? 您正在寻找这样的东西吗?

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

I found a way to do this by using a named Struct. 我找到了一种使用命名的Struct的方法。 So once I named my Struct: 因此,一旦我命名了Struct:

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

I could then do the following: 然后,我可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM