ruby-on-rails – RSpec:在每个上下文之后刷新表或销毁对象

如何删除您创建的对象(在数据库和内存中)

>每次测试后
>每个上下文之后? (在一个上下文中,相互建立测试可能是有意义的)

有没有办法自动做这个?

我有以下问题:

每个测试将条目保存到数据库.接下来的测试取决于这些条目.即使我想要构建依赖于其他测试的测试,我也不能,因为测试执行的顺序是不可控的.

factories.rb:

sequence(:name) { |n| "purchaser #{n}" }

organization_spec.rb:

context "when no supplier exists" do
  it "finds no associated suppliers" do
    purchaser = create(:organization_purchaser)                
    purchaser.partners.empty?.should == true
  end
end

context "when one supplier exists" do
  it "finds one associated suppliers" do
    purchaser = create(:organization_purchaser)      
    supplier = create(:organization_supplier)
    partnership = create(:partnership,organization: purchaser,partner: supplier)         
    purchaser.partners.last.name.should == "purchaser 1"
  end
end

context "when two suppliers exist" do        
  it "finds two associated suppliers" do
    purchaser = create(:organization_purchaser)      
    2.times do |i|
      supplier = create(:organization_supplier)
      partnership = create(:partnership,partner: supplier) 
    end    
    purchaser.partners.last.name.should == "purchaser 2"
  end
end

RSpec输出:

Organization
  #suppliers_for_purchaser
    responds
    when no supplier exists
      finds no associated suppliers
    when two suppliers exist
      finds two associated suppliers
    when one supplier exists
      finds one associated suppliers (FAILED - 1)

Failures:

1) Organization#suppliers_for_purchaser when one supplier exists finds one associated suppliers
 Failure/Error: purchaser.partners.last.name.should == "purchaser 1"
   expected: "purchaser 1"
        got: "purchaser 3" (using ==)

解决方法

你应该使用 Database Cleaner

所有您需要做的是将以下代码添加到您的Rspec配置文件spec_helper.rb中

config.before(:suite) do
  DatabaseCleaner.strategy = :transaction
  DatabaseCleaner.clean_with(:truncation)
end

config.before(:each) do
  DatabaseCleaner.start
end

config.after(:each) do
  DatabaseCleaner.clean
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...