我有一个带有属性访问器的类:
class MyClass
attr_accessor :a, :b
def initialize
@a = 1
@b = 2
end
def update_values options
a = options[:a]
b = options[:b]
end
end我认为在调用update_values之后,a和b应该保留它们的新值:
describe MyClass do
before do
@thing = MyClass.new
end
it 'should set a and b' do
expect(@thing.a).to eq 1
expect(@thing.b).to eq 2
@thing.update_values a: 2, b: 5
expect(@thing.a).to eq 2
expect(@thing.b).to eq 5
end
end这是不可能的-测试失败了:
Failures:
1) MyClass should set a and b
Failure/Error: expect(@thing.a).to eq 2
expected: 2
got: 1
(compared using ==)这不是属性访问器应该工作的方式吗?我遗漏了什么?
发布于 2016-11-01 18:24:48
您只是定义局部变量a和b。
相反,您想要的是为实例变量a和b设置新值。以下是你如何做到这一点:
def update_values options
self.a = options[:a] # or @a = options[:a]
self.b = options[:b] # or @b = options[:b]
end现在:
foo = MyClass.new
#=> #<MyClass:0x007f83eac30300 @a=1, @b=2>
foo.update_values(a: 2, b: 3)
foo #=>#<MyClass:0x007f83eac30300 @a=2, @b=3>https://stackoverflow.com/questions/40366254
复制相似问题