2012-02-04 62 views
1

我正在与Sinatra和RSpec合作。我有这样的LIB/auth.rb如何使attr_accessor仅在测试环境中工作?

class Person 
    attr_accessor :password if ENV['RACK_ENV'] == 'test' 
    .... 

我想执行的时候,我使用RSpec测试这个代码,但它不工作。这是我的规格文件:

describe Person 
    it 'should match the password' do 
     @james = Person.new(foo, 'bar') 
     @james.password.should == 'bar' 
    end 
end 

我不想@james.password是这种模式的外部访问,但要能够从Rspec的文件或在测试环境中访问它。是否有任何代码可以使attr_accessor仅在测试环境中工作?

回答

1

运行测试时,您是否确实设置了ENV['RACK_ENV']

尝试增加

ENV['RACK_ENV'] = 'test' 

您的测试文件的开始。

+0

哇...这是工作。谢谢马特。我不知道ENV ['RACK_ENV']是否为零。 – 2012-02-10 00:37:33

0

我知道这是一个老问题,但不是试图编辑您的代码来为测试工作,您可以使用instance_variable_get
所以,你的天赋应该是这样的:

describe Person 
    it 'should match the password' do 
    @james = Person.new(foo, 'bar') 
    @james.instance_variable_get(:@password).should == 'bar' 
    end 
end 

,它不会要求你Person类中的任何改变!