我正在使用RSpec测试gem中的类级实例变量(和setter).我需要测试以下内容:
显然这里有一个运行订单问题.如果我使用setter更改值,我将失去对默认值的记忆.我可以在setter测试之前将它保存到变量中,然后在结束时重置该值,但是只有在所有setter测试都遵循相同的做法时才能保护我.
测试变量默认值的最佳方法是什么?
这是一个简单的例子:
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
Run Code Online (Sandbox Code Playgroud)
Ism*_*reu 11
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
Run Code Online (Sandbox Code Playgroud)
或者更好的方法是重新加载课程
describe 'items' do
before(:each) do
Object.send(:remove_const, 'Foo')
load 'foo.rb'
end
end
Run Code Online (Sandbox Code Playgroud)
如果你的班级有内部状态,你想测试我发现使用class_variable_get一个很好的方法来接近这个.这不要求您公开类中的任何变量,因此该类可以保持不变.
it 'increases number by one' do
expect(YourClass.class_variable_get(:@@number)).to equal(0)
YourClass.increase_by_one()
expect(YourClass.class_variable_get(:@@number)).to equal(1)
end
Run Code Online (Sandbox Code Playgroud)
我知道这不是你在问题中要求的,但它在标题中,这让我在这里.