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

前端之家收集整理的这篇文章主要介绍了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
原文链接:https://www.f2er.com/ruby/266515.html

猜你在找的Ruby相关文章