RSpec 类变量测试 [英] RSpec Class Variable Testing
问题描述
我正在使用 RSpec 在 gem 中测试类级实例变量(和 setter).我需要测试以下内容:
I'm testing a class level instance variable (and setters) in a gem using RSpec. I need to test the following:
- 如果从未使用过 setter,则会提供正确的默认值.
- 变量可以通过 setter 成功更新.
显然这里存在运行顺序问题.如果我使用 setter 更改值,我会忘记默认值是什么.我可以在 setter 测试之前将它保存到一个变量中,然后在最后重置该值,但这只有在所有 setter 测试都遵循相同的做法时才能保护我.
Obviously there is a run order issue here. If I change the values using the setters, I lose memory of what the default value was. I can save it to a variable before the setter test and then reset the value at the end, but that only protects me if all setter tests follow the same practice.
测试变量默认值的最佳方法是什么?
What is the best way to test the default value of the variable?
这是一个简单的例子:
class Foo
class << self
attr_accessor :items
end
@items = %w(foo bar baz) # Set the default
...
end
describe Foo do
it "should have a default" do
Foo.items.should eq(%w(foo bar baz))
end
it "should allow items to be added" do
Foo.items << "kittens"
Foo.items.include?("kittens").should eq(true)
end
end
推荐答案
class Foo
DEFAULT_ITEMS = %w(foo bar baz)
class << self
attr_accessor :items
end
@items = DEFAULT_ITEMS
end
describe Foo do
before(:each) { Foo.class_variable_set :@items, Foo::DEFAULT_ITEMS }
it "should have a default" do
Foo.items.should eq(Foo::DEFAULT_ITEMS)
end
it "should allow items to be added" do
Foo.items << "kittens"
Foo.items.include?("kittens").should eq(true)
end
end
或者更好的方法是重新加载类
Or maybe a better way is to reload the class
describe 'items' do
before(:each) do
Object.send(:remove_const, 'Foo')
load 'foo.rb'
end
end
这篇关于RSpec 类变量测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!