如何使attr_accessor仅在测试环境中工作?

发布于 2025-01-02 13:34:55 字数 499 浏览 0 评论 0原文

我正在与 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鱼忆七猫命九 2025-01-09 13:34:55

您在运行测试时实际上是否设置了 ENV['RACK_ENV']

尝试添加

ENV['RACK_ENV'] = 'test'

到测试文件的开头。

Are you actually setting ENV['RACK_ENV'] when running your tests?

Try adding

ENV['RACK_ENV'] = 'test'

to the start of your test file.

余生共白头 2025-01-09 13:34:55

我知道这是一个老问题,但您可以使用 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 类进行任何更改!

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:

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

And it wouldn't require any changes to your Person class!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文