Created
May 3, 2016 22:38
-
-
Save ivantsepp/bbf6cc4f1373295a79583fd45878f7d2 to your computer and use it in GitHub Desktop.
Adds fcontext and fshould to shoulda
This file contains 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
# This is inspired from http://qiita.com/osamu_takeuchi/items/256e044a3e802a5abff0 | |
# and https://github.com/seattlerb/minitest-focus. | |
# | |
# Adds `fcontext` and `fshould` methods to shoulda-context. They mark their blocks as focused | |
# and `Context#create_test_from_should_hash` is overriden to add those test names to the | |
# Minitest filter arguments | |
module Shoulda | |
module Context | |
module ClassMethods | |
def focused_contexts | |
@focused_contexts ||= {} | |
end | |
def fcontext(name, &blk) | |
focused_contexts[name] = true | |
context(name, &blk) | |
end | |
def fshould(name_or_matcher, options = {}, &blk) | |
context_name = self.name.gsub(/Test/, "") if self.name | |
focused_contexts[context_name] = true | |
should(name_or_matcher, options, &blk) | |
end | |
alias_method :context!, :fcontext | |
alias_method :should!, :fshould | |
end | |
class Context | |
def focused_shoulds | |
@focused_shoulds ||= {} | |
end | |
def focused_contexts | |
@focused_contexts ||= {} | |
end | |
def fcontext(name, &blk) | |
focused_contexts[name] = true | |
context(name, &blk) | |
end | |
alias_method :context!, :fcontext | |
def fshould(name_or_matcher, options = {}, &blk) | |
focused_shoulds[name_or_matcher] = true | |
should(name_or_matcher, options, &blk) | |
end | |
alias_method :should!, :fshould | |
def is_focused? | |
parent.focused_contexts[name] || (parent && parent.respond_to?(:is_focused?) && parent.is_focused?) | |
end | |
alias_method :old_create_test_from_should_hash, :create_test_from_should_hash | |
def create_test_from_should_hash(should) | |
old_create_test_from_should_hash(should) | |
if focused_shoulds[should[:name]] || is_focused? | |
test_name = [test_name_prefix, full_name, "should", "#{should[:name]}. "].flatten.join(' ').to_sym | |
test_unit_class.add_to_filter(test_name) | |
end | |
end | |
end | |
end | |
end | |
# This is copied from https://github.com/seattlerb/minitest-focus | |
class Minitest::Test # :nodoc: | |
@@filtered_names = [] # :nodoc: | |
def self.add_to_filter(name) | |
@@filtered_names << "#{self}##{name}" | |
filter = "/^(#{Regexp.union(@@filtered_names).source})$/" | |
index = ARGV.index("-n") | |
if index | |
warn "NOTE: Found `-n <regexp>` arg. This breaks under Rake::TestTask" | |
end | |
index = ARGV.index { |arg| arg =~ /^-n/ } | |
ARGV.delete_at index if index | |
ARGV << "-n=#{filter}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment