实例变量和 Rspec 2.x 的问题 [英] Issue with Instance variable and Rspec 2.x
问题描述
我使用的是 Rspec 2.0.我不明白作用域在这里是如何工作的......不知何故,您可以读取任何块中的变量,但我无法更新它?这是为什么?
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
推荐答案
根据 RSpecbook, before(:all)
:
... 运行一次,并且只在它的自己的 Object 实例,但它的实例变量被复制到每个例子中的例子跑步.使用此注意事项:一般来说,我们希望每个示例完全隔离运行另一个.一旦我们开始跨示例共享状态,意想不到的事情开始发生.
... gets run once and only once in its own instance of Object, but its instance variables get copied to each instance in which the examples are run. A word of caution in using this: in general, we want to have each example run in complete isolation from one another. As soon as we start sharing state across examples, unexpected things begin to happen.
所以在你的例子中 @blah
在每个测试运行之前被复制,因此分配给它的值不会从一个例子转移到另一个例子.
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):
it "gets a token" do
@token = OAuth.some_method_that_returns_a_token
end
it "uses that token to access some OAuth feature" do
result = OAuth.some_feature(@token)
result.should be_something_something
end
这听起来像是对 OAuth 的测试,而不是对您的代码的测试.您应该考虑删除 some_feature
方法(更多空气代码):
This smells like a test of OAuth, not of your code. You should consider stubbing out the some_feature
method (more air code):
it "responds in some way when I use a valid token" do
@token = mock('token')
OAuth.should_receive(:some_feature).with(@token).and_return("success")
result = my_code_which_uses_ouath(@token)
result.should == "success"
end
这篇关于实例变量和 Rspec 2.x 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!