清除 Rspec 示例之间的类实例变量
我正在为我的一个扩展 ActiveRecord 的 gem 编写规范。它必须做的事情之一是设置一个类实例变量,如下所示:
class MyModel < ActiveRecord::Base
@foo = "asd"
end
现在,当我在一个 it“应该”{}
中设置 @foo 时,它会保留到下一个。我知道这是正常的 Ruby 行为,但我认为 RSpec 有一些魔力可以清除规范之间的所有内容。我想知道如何在所有测试中重复使用单个 AR 模型(因为创建一堆表会很痛苦),同时确保在每次测试之间清除 @foo。我需要手动执行此操作吗?
I'm writing specs for a gem of mine that extends ActiveRecord. One of the things it has to do is set a class instance variable like so:
class MyModel < ActiveRecord::Base
@foo = "asd"
end
Right now when I set @foo in one it "should" {}
it persists to the next one. I understand this is normal Ruby behavior but I thought RSpec had some magic that cleaned everything out in between specs. I'd like to know how I can re-use a single AR model for all my tests (since creating a bunch of tables would be a pain) while being sure that @foo is being cleared between each test. Do I need to do this manually?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最终在辅助类中生成了一个方法,该方法使用 Class.new 生成新类,因此我可以确定在测试之间不会留下任何内容。
I wound up generating a method in my helper class that generated new classes with Class.new, so I could be sure that nothing was being left over in between tests.
您应该充分利用
after :each
块。You should simply make good use of the
after :each
block.