如何使attr_accessor仅在测试环境中工作?
我正在与 Sinatra 和 RSpec 合作。我在 lib/auth.rb 中有此代码,
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
仅在测试环境中工作?
I'm working with Sinatra and RSpec. I have this in lib/auth.rb
class Person
attr_accessor :password if ENV['RACK_ENV'] == 'test'
....
I want to execute this code when I'm testing with Rspec, but it doesn't work. This is my spec file:
describe Person
it 'should match the password' do
@james = Person.new(foo, 'bar')
@james.password.should == 'bar'
end
end
I don't want @james.password
to be accessible outside of this model, but to be able to access it from the Rspec file or in the testing environment. Is there any code to make attr_accessor
work only in the testing environment?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在运行测试时实际上是否设置了
ENV['RACK_ENV']
?尝试添加
到测试文件的开头。
Are you actually setting
ENV['RACK_ENV']
when running your tests?Try adding
to the start of your test file.
我知道这是一个老问题,但您可以使用
instance_variable_get
。因此,您的规范将如下所示:
并且不需要对您的
Person
类进行任何更改!I know this is an old question but rather than trying to edit your code to work for the test, you could use
instance_variable_get
.So, your spec would look like this:
And it wouldn't require any changes to your
Person
class!