Rails 测试有 setup_class/teardown_class 吗?

Posted

技术标签:

【中文标题】Rails 测试有 setup_class/teardown_class 吗?【英文标题】:Is there a setup_class/teardown_class for Rails tests? 【发布时间】:2010-10-31 19:33:40 【问题描述】:

我需要为某些类或系统范围的 Rails 测试设置和拆卸方法,但我只找到了一种方法来定义适用于每个测试级别的常规安装/拆卸方法。

例如:

class ActiveSupport::TestCase
  setup do
    puts "Setting up"
  end

  teardown do
    puts "tearing down"
  end
end

将为每个测试用例执行输出,但我想要类似的东西:

class ActiveSupport::TestCase
  setup_fixture do
    puts "Setting up"
  end

  teardown_fixture do
    puts "tearing down"
  end
end

它将执行 setup_fixture before所有测试方法,然后执行 teardown_fixture after所有测试方法。

有没有这样的机制?如果没有,有没有一种简单的方法可以修改这个机制?

【问题讨论】:

【参考方案1】:

有几个流行的测试框架建立在Test::Unit 之上并提供这种行为:

RSpec

describe "A Widget" do
  before(:all) do
    # stuff that gets run once at startup
  end
  before(:each) do
    # stuff that gets run before each test
  end
  after(:each) do
    # stuff that gets run after each test
  end
  after(:all) do
    # stuff that gets run once at teardown
  end
end

Test/Spec

context "A Widget" do
  # same syntax as RSpec for before(:all), before(:each), &c.
end

【讨论】:

【参考方案2】:

我认为 rails 为固定装置提供了这样的功能。您可以通过说来使用固定装置

固定装置:用户

在您的测试文件中

除此之外你还可以使用

默认设置 #.... 结尾

也在你的测试文件中,

【讨论】:

以上是关于Rails 测试有 setup_class/teardown_class 吗?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Rails 中测试助手?

Rails 4:如何重置测试数据库?

在大型 Rails 应用程序中加速 RSpec 测试

Rails 3.1,RSpec:测试模型验证

带有载波的 Rails 3 测试夹具?

Ruby on Rails 单元测试