0

I met a very strange issue when writing test using RSpec. Assume that I have 2 models: Company and Item with association company has_many items. I also set up database_cleaner with strategy transaction. My RSpec version is 2.13.0, database_cleaner version is 1.0.1, rails version is 3.2.15, factory_girl version is 4.2.0. Here is my test:

let(:company) { RSpec.configuration.company }
context "has accounts" do
  it "returns true" do
    company.items << FactoryGirl.create(:item)
    company.items.count.should > 0
  end
end
context "does not have accounts" do
  it "returns false" do
    company.items.count.should == 0
  end
end

end

I set up an initial company to rspec configuration for using in every test because I don't want to recreate it in every tests because creating a company takes a lot of time(due to its callbacks and validations). The second test fails because item is not cleaned from the database after the first test. I don't understand why. If I change line company.items << FactoryGirl.create(:item) to FactoryGirl.create(:item, company: company), the it passes. So can any body explain for me why transaction isn't rollbacked in the first situation. I'm really messed up

Thanks. I really appreciate.

4

1 回答 1

0

我认为问题不在于回滚,我想知道是否company.items可以在 s 之间存储它的值,context但我不确定。

我无法快速复制它,所以我想请你:

  1. 检查log/test.log何时执行回滚
  2. 制作了多少个INSERTscompany.items << FactoryGirl.create(:item)
  3. 而不是在第一次测试>中改变<这种方式:company.items.count.should < 0它会使测试失败,但你会得到计数值。是 1 还是 2 ?
  4. 如果您与/之类的模型之间存在关系,那么Company我建议您只使用which 也应该为它创建公司:Itemhas_manybelongs_tobuild(:item)

例如:

let(:item) { FactoryGirl.build(:item) }
context "has accounts"
it "returns true" do
  item.save
  Company.items.count.should == 1
end

不要忘记在工厂包括association :company生产线:item

暗示:

添加到spec_helper.rb

RSpec.configure do |config|
  # most omitted
  config.include FactoryGirl::Syntax::Methods

您可以像这样直接调用任何 FactoryGirl 方法:

let(:item) { build(:item) }
于 2014-04-27T05:17:03.357 回答