实例变量和 Rspec 2.x 的问题
我正在使用 Rspec 2.0。我不明白作用域在这里是如何工作的...不知何故,您可以读取任何块中的变量,但我无法更新它?这是为什么?
describe 'Test App' do
before(:all) do
@test= :blah
end
it 'test' do
@test=:bye
p @test # => prints bye
end
it 'test' do
p @test # => prints blah rather than bye...
end
end
I am using Rspec 2.0. I am not understanding how the scope works here... Somehow you can read the variable in any block but I cannot update it? why is that?
describe 'Test App' do
before(:all) do
@test= :blah
end
it 'test' do
@test=:bye
p @test # => prints bye
end
it 'test' do
p @test # => prints blah rather than bye...
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据RSpec 书,
before(:all)
:因此,在您的示例中,在运行每个测试之前都会复制
@blah
,因此分配给它的值不会从一个示例转移到另一个示例。看起来你想做这样的事情(空中代码):
这听起来像是 OAuth 的测试,而不是你的代码的测试。您应该考虑删除
some_feature
方法(更多空中代码):According to the RSpec book,
before(:all)
:So in your examples
@blah
is copied before each test is run, thus values assigned to it do not carry over from one example to another.It seems like you want to do something like this (air code):
This smells like a test of OAuth, not of your code. You should consider stubbing out the
some_feature
method (more air code):这实际上是 ruby 的所有属性,而不是 RSpec 本身。 before 块是在执行每个 it 块之前调用的回调。这就是你的变量被实例化为
blah
的方式。当您在第二个测试中将其定义为再见时,当下一个测试再次调用 before 块时,该定义将被重新定义。This is really all a property of ruby and not RSpec itself. The before block is a callback invoked before each it block is executed. So that is how your variable is instantiated to
blah
. When in your second test your defined it to be bye that definition is redefined when the before block is invoked again for the next test.我遇到了同样的问题并用哈希解决了它,我在其中更改了值:
I run into the same problem and solved it with Hash in which I change values: