Skip to content

Instantly share code, notes, and snippets.

@courtenay
Last active September 18, 2018 03:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save courtenay/7343845 to your computer and use it in GitHub Desktop.
Save courtenay/7343845 to your computer and use it in GitHub Desktop.
before(:all) hacks for minitest
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
@courtenay
Copy link
Author

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

@grosser
Copy link

grosser commented Nov 5, 2014

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