简体   繁体   English

Rspec,FactoryGirl:FactoryGirl.create in before(:all)不是持久记录?

[英]Rspec, FactoryGirl: FactoryGirl.create in before(:all) isn't persisting records?

I'm trying to create a few records for some tests I have for my Image object. 我正在尝试为我的Image对象进行一些测试创建一些记录。 However, it seems like they don't persist: 但是,似乎他们不坚持:

describe Image do
    before(:all) do
      for i in 0..2
        FactoryGirl.create(:image)
      end

      puts Image.count
    end

    it "blah blah blah" do
      puts Image.count
    end

    it "blah blah blah 2" do
      puts Image.count
    end

In the above example, the first call to Image.count returns 3; 在上面的例子中,对Image.count的第一次调用返回3; subsequent calls return 0. The example works when I use before(:each) , however I feel like before(:all) should really be what I want. 后续调用返回0.该示例在我使用before(:each) ,但我觉得before(:all)应该是我想要的。

You rarely if ever want to use before(:all). 你之前很少想要使用(:all)。 You want to use before(:each). 你想在之前使用(:每个)。 before(:all) is run when the context/describe block begins, before(:each) is run before each spec inside it. before(:all)在context / describe块开始时运行,之前(:each)在每个内部规范之前运行。 This is why your are getting 0 for the second and third calls. 这就是为什么第二次和第三次调用你得到0的原因。

There is another important reason that you don't want to use before(:all) which is that you don't want your tests to run together. 还有另一个重要原因是你不想在之前使用(:all),这是你不希望你的测试一起运行的。 This means that the examples become bound together, which is an absolute no-no in testing. 这意味着示例被绑定在一起,这在测试中是绝对禁止的。 You should really only ever use before(:all) to set up things that are global collaborators but not the things that you are describing in the examples. 您之前应该只使用(:all)设置全局协作者的内容,而不是您在示例中描述的内容。

Short Answer: Use before(:each) 简答:使用之前(:每个)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM