Module: TestProf::LetItBe
- Defined in:
- lib/test_prof/recipes/rspec/let_it_be.rb
Overview
Just like ‘let`, but persist the result for the whole group. NOTE: Experimental and magical, for more control use `before_all`.
Constant Summary collapse
- PREFIX =
Use uniq prefix for instance variables to avoid collisions We want to use the power of Ruby’s unicode support) And we love cats!)
RUBY_ENGINE == 'jruby' ? "@__jruby_is_not_cat_friendly__" : "@😸"
Class Method Summary collapse
- .module_for(group) ⇒ Object
-
.supported? ⇒ Boolean
Only works with RSpec 3.2.0.
Instance Method Summary collapse
- #define_let_it_be_methods(identifier, reload: false, refind: false) ⇒ Object
- #let_it_be(identifier, **options, &block) ⇒ Object
Class Method Details
.module_for(group) ⇒ Object
11 12 13 14 15 |
# File 'lib/test_prof/recipes/rspec/let_it_be.rb', line 11 def module_for(group) modules[group] ||= begin Module.new.tap { |mod| group.prepend(mod) } end end |
.supported? ⇒ Boolean
Only works with RSpec 3.2.0
18 19 20 |
# File 'lib/test_prof/recipes/rspec/let_it_be.rb', line 18 def supported? TestProf::Utils.verify_gem_version('rspec-core', at_least: '3.2.0') end |
Instance Method Details
#define_let_it_be_methods(identifier, reload: false, refind: false) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/test_prof/recipes/rspec/let_it_be.rb', line 52 def define_let_it_be_methods(identifier, reload: false, refind: false) let_accessor = -> { instance_variable_get(:"#{PREFIX}#{identifier}") } if reload let_accessor = lambda do record = instance_variable_get(:"#{PREFIX}#{identifier}") next unless record.is_a?(::ActiveRecord::Base) record.reload end end if refind let_accessor = lambda do record = instance_variable_get(:"#{PREFIX}#{identifier}") next unless record.is_a?(::ActiveRecord::Base) record.class.find(record.send(record.class.primary_key)) end end LetItBe.module_for(self).module_eval do define_method(identifier) do # Trying to detect the context (couldn't find other way so far) if @__inspect_output =~ /\(:context\)/ instance_variable_get(:"#{PREFIX}#{identifier}") else # Fallback to let definition super() end end end let(identifier, &let_accessor) end |
#let_it_be(identifier, **options, &block) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/test_prof/recipes/rspec/let_it_be.rb', line 33 def let_it_be(identifier, **, &block) unless LetItBe.supported? TestProf.log :warn, "let_it_be requires RSpec >= 3.2.0. Fallback to let!" return let!(identifier, &block) end initializer = proc do instance_variable_set(:"#{PREFIX}#{identifier}", instance_exec(&block)) end if within_before_all? before(:all, &initializer) else before_all(&initializer) end define_let_it_be_methods(identifier, **) end |