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

发布时间:2019-06-08 整理:脚本之家
脚本之家收集整理的这篇文章主要介绍了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

总结

以上是脚本之家为你收集整理的ruby-on-rails – RSpec:在每个上下文之后刷新表或销毁对象全部内容,希望文章能够帮你解决ruby-on-rails – RSpec:在每个上下文之后刷新表或销毁对象所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

脚本之家官方公众号

微信公众号搜索 “ 程序精选 ” ,选择关注!

微信公众号搜索 “ 程序精选 ” ,选择关注!
精选程序员所需精品干货内容!

脚本之家官方公众号

微信公众号搜索 “ 程序精选 ” ,选择关注!

微信公众号搜索 “ 程序精选 ”
精选程序员所需精品干货内容!