简体   繁体   中英

Is there a setup_class/teardown_class for Rails tests?

I need to have a setup and teardown method for some Rails tests that is class or system wide, yet I have only found a way to define a regular setup/teardown that works on a per test level.

For example:

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

  teardown do
    puts "tearing down"
  end
end

will execute the outputs for each test case, but I would like something like:

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

  teardown_fixture do
    puts "tearing down"
  end
end

which would execute the setup _ fixture before all test methods, and then execute teardown _ fixture after all test methods.

Is there any such mechanism? If not, is there an easy way to monkey patch this mechanism in?

There are several popular test frameworks that build on Test::Unit and provide this behavior:

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

I think rails provides such a functionality for fixtures. You can use fixtures by saying

fixtures :users

in your test files

and besides you can also use

def setup
  #....
end

in your test files as well,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM