gpt4 book ai didi

ruby-on-rails - RSpec 3.2 中的 stub 实例变量

转载 作者:行者123 更新时间:2023-12-02 06:16:31 28 4
gpt4 key购买 nike

我在 Rails 中使用 RSpec 3.2,想知道如果实例变量不能通过 getter 方法公开访问(例如使用 attr_accessor 或类似方法),我如何 stub 实例变量。

考虑下面的简单示例 -

require 'rails_helper'

class A
def initialize
@x = 3
end

def add(n)
sum = @x + n
puts "Sum is #{sum}"
sum
end
end


RSpec.describe A do
before(:all) do
@a = A.new
end

it 'computes the sum correctly' do
# For this test I want to stub the value of @x and return 5
allow(@a).to receive(:x) { 5 }
# 5 + 8 should return 13
expect(@a.add(8)).to eq(13)
end
end

试图 stub @x在这种情况下是不可能的,因为该类永远不会收到 x 的消息或方法调用. RSpec 输出证实了这一点 -
Failures:

1) A computes the sum correctly
Failure/Error: allow(@a).to receive(:@x) { 5 }
#<A:0x007fe6e66ab8d0 @x=3> does not implement: @x
# ./spec/unit/test_spec.rb:25:in `block (2 levels) in <top (required)>'

我可以通过创建实例变量 @x 来解决这个问题。可访问( attr_accesssor :x )并将调用替换为 @xself.x ,但这似乎很老套,在我更复杂的实现中可能是不可能的。

有没有更好的方法来 stub 这个?

谢谢!

最佳答案

我认为这不是正确的做法。 Rspec 应该测试类的接口(interface)行为,而不是内部实现。

由于您没有使用访问器,您可以使用 #instance_variable_set & #instance_variable_get 操作和获取实例变量。

获取和设置如下:

@a.instance_variable_set(:@x, 5)
@a.instance_variable_get(:@x)
#=> 5

在您的代码中:
@a.instance_variable_set(:@x, 5)
expect(@a.add(8)).to eq(13)

关于ruby-on-rails - RSpec 3.2 中的 stub 实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333153/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com