如何设置在方法测试中使用的私有实例变量? [英] How to set private instance variable used within a method test?
问题描述
给出一个带有几个实例变量和一些方法的类。可以通过 attr_reader
和 attr_accessor
设置一些实例变量的访问权限。
一些私有实例变量在一个实例方法中设置并在另一个方法中读取/利用。
Given a class with a couple of instance variables and some methods. Some instance variables are set accessible via attr_reader
and attr_accessor
. Thus the others are private.
Some of the private instance variables get set within one of the instance methods and read/utilized within another method.
为了进行测试,我使用了RSpec。由于我还是Ruby的新手,并且想让所有事情都做对,因此我定义了相当精细的测试。因此,对于每个实例方法,我都有一个 describe
块,它们本身被划分为 context
s的子集, it
s。一般环境先决条件用 before
定义。
For testing I'm using RSpec. As I'm still new to Ruby and want to get all things right, I defined my tests being rather fine-grained. Thus I've got one describe
block for each instance method, which themselves are partitioned into a subset of context
s and it
s. General environmental preconditions are defined with before
.
但是,当测试其中一种方法时,该方法正在使用但未使用设置一个私有变量,我需要调用另一个方法,即设置此变量。对我来说,这似乎超重了,而且不是模块化的。
However, when testing one of the methods, which is utilizing but not setting one of the private variables, I need to call the other method, which is setting this variable. This seems rather overweight and not modular for me.
有没有一种方法可以将私有实例变量强制为某个值。类似于 提取,使用 Object :: instance_eval(:var)
的私有实例变量的值。
Is there a way of forcing a private instance variable to a certain value. Similar to "ripping out" the value of a private instance variable with Object::instance_eval(:var)
.
推荐答案
在回答问题时,设置实例变量的最简单方法是使用 instance_eval
方法:
As you answered in your question the easiest way to set instance variable is with instance_eval
method:
obj.instance_eval('@a = 1')
另一种方法是使用instance_variable_set:
Another way is to use instance_variable_set:
obj.instance_variable_set(:@a, 1)
但是我不建议您这样做。规范全部涉及测试对象的行为以及通过使用 instance_eval
破坏类封装来测试行为,这将使您的测试更加脆弱且依赖于实现。
But I would not recommend to do this in your specs. Specs are all about testing behavior of an object and testing behaviour by breaking class encapsulation with instance_eval
will make your tests more fragile and implementation dependent.
对象状态隔离的另一种方法是存根访问器方法:
Alternative approach to object state isolation is to stub accessor methods:
class UnderTest
attr_accessor :a
def test_this
do_something if a == 1
end
end
#in your test
under_test = UnderTest.new
under_test.stub(:a).and_return(1)
这篇关于如何设置在方法测试中使用的私有实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!