如何在加载灯具之后但在第一次测试开始之前运行一段代码?

时间:2017-08-08 17:00:02

标签: ruby-on-rails ruby ruby-on-rails-4

我使用灯具作为我的测试数据。在我的灯具加载到db之后,但在任何测试运行之前,我需要进行额外的初始化步骤。额外的初始化数据应该可用于所有测试。

test_helper.rb中

class ActiveSupport::TestCase
  fixtures :all
end

user_test.rb

require 'test_helper'
class UserTest < ActiveSupport::TestCase
   test do
     # here I use my extra initialization data
     # it takes a lot of effort to create the data
     # I'd like this data is available to every test in initial state
   end
end

这是日志。我标记了我需要进行初始化的地方。

D, [2017-08-09T07:54:19.910545 #94547] DEBUG -- :    (8.8ms)  ALTER TABLE "mytable" DISABLE TRIGGER ALL;
D, [2017-08-09T07:54:20.151100 #94547] DEBUG -- :    (0.2ms)  BEGIN
D, [2017-08-09T07:54:20.153111 #94547] DEBUG -- :   Fixture Delete (0.3ms)  DELETE FROM "mytable"
D, [2017-08-09T07:54:21.231062 #94547] DEBUG -- :   Fixture Insert (0.2ms)  INSERT INTO "mytable" ...
D, [2017-08-09T07:54:21.234581 #94547] DEBUG -- :    (2.1ms)  COMMIT
D, [2017-08-09T07:54:21.239761 #94547] DEBUG -- :    (4.1ms)  ALTER TABLE "mytable" ENABLE TRIGGER ALL;
# <-- I need my initialization here
D, [2017-08-09T07:54:21.256388 #94547] DEBUG -- :    (0.2ms)  BEGIN
I, [2017-08-09T07:54:21.256510 #94547]  INFO -- : -----------------------------
I, [2017-08-09T07:54:21.256550 #94547]  INFO -- : DummyTest: test_my_dummy_test
I, [2017-08-09T07:54:21.256583 #94547]  INFO -- : -----------------------------
(dbg) my dummy test: setup
(dbg) my dummy test
(dbg) my dummy test: teardown
D, [2017-08-09T07:54:21.257013 #94547] DEBUG -- :    (0.1ms)  ROLLBACK

1 个答案:

答案 0 :(得分:0)

到目前为止,找到的最佳解决方案是将以下方法添加到ActiveSupport :: TestCase类

def enlist_fixture_connections(*)
  result = super
  # you code here
  result
end

您的代码将在夹具初始化之后和每次测试之前执行,但不会在测试的事务中执行。