gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:40:53 26 4
gpt4 key购买 nike

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

  • 每次测试后
  • AND 在每个上下文之后? (在某种情况下,相互构建测试可能是有意义的)

是否有自动执行此操作的方法?

我有以下问题:

每个测试都会将条目保存到数据库中。下一个测试则取决于这些条目。即使我想构建依赖于其他测试的测试,我也做不到,因为测试的执行顺序是不可控的。

工厂.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, organization: purchaser, 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

更新

从 Rails 5.1 开始,如果您使用 config.use_transactional_tests,则不需要这样做

https://github.com/rails/rails/pull/19282

关于ruby-on-rails - RSpec:在每个上下文之后刷新表/销毁对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14366524/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com