RSpec类变量测试

我正在使用RSpec测试gem中的类级实例变量(和setter)。 我需要测试以下内容:

  1. 如果从未使用过setter,则会提供正确的默认值。
  2. 可以通过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 

 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::DFAULT_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 

或者更好的方法是重新加载课程

 describe 'items' do before(:each) do Object.send(:remove_const, 'Foo') load 'foo.rb' end end 

如果你的类有内部状态,你想测试我发现使用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 

我知道这不是你在问题中要求的,但它在标题中,这让我在这里。