Last active
September 18, 2018 03:35
-
-
Save courtenay/7343845 to your computer and use it in GitHub Desktop.
before(:all) hacks for minitest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Fixtures | |
# | |
# Set up fixtures that will be defined once during startup | |
# and (perhaps) rolled back at the beginning of each test run | |
# | |
def fixtures &block | |
if block_given? | |
instance_eval &block | |
@fixtures = {} | |
(instance_variables - [:@fixtures]).each do |fresh| | |
@fixtures[fresh] = instance_variable_get(fresh) | |
end | |
else | |
@fixtures | |
end | |
end | |
end | |
# Before each test, look at the class-variables defined | |
# and just tragically set them in the instance | |
# | |
module TestRunner | |
def before_setup | |
# todo: start transaction here | |
super | |
self.class.fixtures.each do |key, val| | |
instance_variable_set "#{key}", val | |
end | |
end | |
def before_teardown | |
# todo: rollback transaction here | |
super | |
end | |
end | |
# Then include it into your test | |
class MiniTest::Test | |
extend Fixtures | |
include TestRunner | |
end | |
# And define your test | |
require 'minitest/autorun' | |
class ApiTest < MiniTest::Test | |
fixtures do | |
@test = 5 | |
end | |
def test_fixtures | |
assert_equal @test, 5 | |
@test = 6 # let's see if it leaks | |
end | |
def test_fixtures_again | |
assert_equal @test, 5 | |
@test = 7 | |
end | |
end |
If you can come up with a nice / intuitive solution, please add to https://github.com/grosser/maxitest, one of the last todos.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is not perfect because the block instance_eval runs when the class is defined and the file is loaded, rather than right before the file's tests are run. this could be mitigated by saving the block and memoizing it