一些其他测试后如何运行测试?

时间:2018-01-13 19:42:33

标签: ruby-on-rails ruby rspec

我已经制作了rspec扩展,用于制作和加载数据库转储。

用法示例:

  • 一个测试发出命令并填充db
  • 我想在下订单后测试管理页面

现在我正在使用它:

# spec/support/config/db_dumper.rb
module DbDumper
  def make_dump(name)
    assert_executable('pg_dump')

    path = dump_path(name)

    FileUtils.mkdir_p(File.dirname(path))

    options = [
      # '--verbose',
      '--clean',
      '--no-owner',
      '--no-acl',
      '--format=c',
      "--dbname=#{ENV['DATABASE_URL']}"
    ].join(' ')

    cmd = "pg_dump #{options} > #{path}"

    puts "Make dump with: #{cmd}"
    system cmd
  end

  def load_dump(name)
    assert_executable('pg_restore')

    path = dump_path(name)

    options = [
      # '--verbose',
      '--clean',
      '--no-owner',
      '--no-acl',
      '--format=c',
      "--dbname=#{ENV['DATABASE_URL']}"
    ].join(' ')

    cmd = "pg_restore #{options} #{path}"

    puts "Restore dump with: #{cmd}"
    system cmd
  end

  def dump_exists(name)
    path = dump_path(name)
    File.exist?(path)
  end

  private

  def dump_path(name)
    file = "#{name}.dump"
    Rails.root.join('spec', 'fixtures', 'dumps', file)
  end

  def assert_executable(name)
    present = `which #{name}`.strip.present?
    raise "No executable #{name}" unless present
  end
end

RSpec.configure do |c|
  c.include DbDumper
end

RSpec.configure do |c|
  c.include DbDumper
end

# spec/features/checkout_spec.rb
feature 'Checkout page' do
  scenario 'can make order' do
    # ... make order
    make_dump('checkout')
  end
end

# spec/features/admin_spec.rb
feature 'Admin page' do
  before { load_dump('checkout') }
  scenario 'shows order' do
    # ... test
  end
end

但我想写这样的东西

# spec/features/checkout_spec.rb
feature 'Checkout page' do
  scenario 'can make order', id: 'checkout' do
    # ... make order
  end
end

# spec/features/admin_spec.rb
feature 'Admin page' do
  scenario 'shows order', after: 'checkout' do
    # ... test
  end
end

这个伪代码

RSpec.configure do |config|
  config.after(:example, :id) do
    id = example.metadata[:id]
    make_dump(id)
  end

  config.prepend_before(:example, :after) do
    id = example.metadata[:after]

    unless dump_exists(id)
      # run test with id, this test will make dump
    end

    load_dump(id)
  end
end

但是在钩子之前运行其他一些测试是不好的,也许是不可能的。有人能帮助我吗?

0 个答案:

没有答案