gpt4 book ai didi

ruby-on-rails - rspec DatabaseCleaner 跳过清理例如组元数据标签

转载 作者:行者123 更新时间:2023-12-04 06:33:05 29 4
gpt4 key购买 nike

如何标记示例组,以便在每个示例之间不清理数据库,而是在整个组之前和之后清理数据库?未标记的规范应该清理每个示例之间的数据库。

我想写:

describe 'my_dirty_group', :dont_clean do
...
end

所以在我的 spec_helper.rb 中我放了:
  config.use_transactional_fixtures = false

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

config.before(:suite, dont_clean: true) do
DatabaseCleaner.clean
end

config.after(:suite, dont_clean: true) do
DatabaseCleaner.clean
end

config.before(:each, dont_clean: nil) do
DatabaseCleaner.start
end

config.before(:each, dont_clean: nil) do
DatabaseCleaner.clean
end

问题在于 dont_clean: nil当未指定元数据标签时,spec_helper 中的(或 false)块不会运行。在示例之间进行清洁之前,是否有另一种方法来检查 :dont_clean 的存在?

最佳答案

概括

您可以在整个示例块上设置自定义元数据,然后使用 self.class.metadata 访问 RSpec 配置中的元数据。用于条件逻辑。

代码

使用这些 gem 版本:

$ bundle exec gem list | grep -E '^rails |^rspec-core |^database'
database_cleaner (1.4.0)
rails (4.2.0)
rspec-core (3.2.0)

以下对我有用:

文件:spec/spec_helper.rb

RSpec.configure do |config|

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

config.before(:all) do
# Clean before each example group if clean_as_group is set
if self.class.metadata[:clean_as_group]
DatabaseCleaner.clean
end
end

config.after(:all) do
# Clean after each example group if clean_as_group is set
if self.class.metadata[:clean_as_group]
DatabaseCleaner.clean
end
end

config.before(:each) do
# Clean before each example unless clean_as_group is set
unless self.class.metadata[:clean_as_group]
DatabaseCleaner.start
end
end

config.after(:each) do
# Clean before each example unless clean_as_group is set
unless self.class.metadata[:clean_as_group]
DatabaseCleaner.clean
end
end

end

文件:spec/models/foo_spec.rb

require 'spec_helper'

describe 'a particular resource saved to the database', clean_as_group: true do

it 'should initially be empty' do
expect(Foo.count).to eq(0)
foo = Foo.create()
end

it 'should NOT get cleaned between examples within a group' do
expect(Foo.count).to eq(1)
end

end

describe 'that same resource again' do

it 'should get cleaned between example groups' do
expect(Foo.count).to eq(0)
foo = Foo.create()
end

it 'should get cleaned between examples within a group in the absence of metadata' do
expect(Foo.count).to eq(0)
end

end

关于ruby-on-rails - rspec DatabaseCleaner 跳过清理例如组元数据标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17191671/

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