code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def fail_including(*snippets) raise_error( RSpec::Expectations::ExpectationNotMetError, a_string_including(*snippets) ) end
Matches if an expectation fails including the provided message @example expect { some_expectation }.to fail_including("portion of some failure message")
fail_including
ruby
rspec/rspec-expectations
lib/rspec/matchers/fail_matchers.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/fail_matchers.rb
MIT
def message_with_diff(message, differ) diff = diffs(differ) message = "#{message}\n#{diff}" unless diff.empty? message end
@api private Returns message with diff(s) appended for provided differ factory and actual value if there are any @param [String] message original failure message @param [Proc] differ @return [String]
message_with_diff
ruby
rspec/rspec-expectations
lib/rspec/matchers/multi_matcher_diff.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/multi_matcher_diff.rb
MIT
def matches?(actual) @actual = actual match(expected, actual) end
@api private Indicates if the match is successful. Delegates to `match`, which should be defined on a subclass. Takes care of consistently initializing the `actual` attribute.
matches?
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/base_matcher.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/base_matcher.rb
MIT
def match_unless_raises(*exceptions) exceptions.unshift Exception if exceptions.empty? begin yield true rescue *exceptions => @rescued_exception false end end
@api private Used to wrap a block of code that will indicate failure by raising one of the named exceptions. This is used by rspec-rails for some of its matchers that wrap rails' assertions.
match_unless_raises
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/base_matcher.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/base_matcher.rb
MIT
def description desc = EnglishPhrasing.split_words(self.class.matcher_name) desc << EnglishPhrasing.list(@expected) if defined?(@expected) desc end
@api private Generates a description using {EnglishPhrasing}. @return [String]
description
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/base_matcher.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/base_matcher.rb
MIT
def improve_hash_formatting(inspect_string) inspect_string.gsub(/(\S)=>(\S)/, '\1 => \2') end
`{ :a => 5, :b => 2 }.inspect` produces: {:a=>5, :b=>2} ...but it looks much better as: {:a => 5, :b => 2} This is idempotent and safe to run on a string multiple times.
improve_hash_formatting
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/base_matcher.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/base_matcher.rb
MIT
def failure_message "expected #{description_of @actual} to #{description}".dup end
@api private Provides a good generic failure message. Based on `description`. When subclassing, if you are not satisfied with this failure message you often only need to override `description`. @return [String]
failure_message
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/base_matcher.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/base_matcher.rb
MIT
def failure_message_when_negated "expected #{description_of @actual} not to #{description}".dup end
@api private Provides a good generic negative failure message. Based on `description`. When subclassing, if you are not satisfied with this failure message you often only need to override `description`. @return [String]
failure_message_when_negated
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/base_matcher.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/base_matcher.rb
MIT
def inclusive @less_than_operator = :<= @greater_than_operator = :>= @mode = :inclusive self end
@api public Makes the between comparison inclusive. @example expect(3).to be_between(2, 3).inclusive @note The matcher is inclusive by default; this simply provides a way to be more explicit about it.
inclusive
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/be_between.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/be_between.rb
MIT
def exclusive @less_than_operator = :< @greater_than_operator = :> @mode = :exclusive self end
@api public Makes the between comparison exclusive. @example expect(3).to be_between(2, 4).exclusive
exclusive
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/be_between.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/be_between.rb
MIT
def of(expected) @expected = expected @tolerance = @delta @unit = '' self end
@api public Sets the expected value.
of
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/be_within.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/be_within.rb
MIT
def percent_of(expected) @expected = expected @tolerance = @expected.abs * @delta / 100.0 @unit = '%' self end
@api public Sets the expected value, and makes the matcher do a percent comparison.
percent_of
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/be_within.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/be_within.rb
MIT
def by(expected_delta) ChangeRelatively.new(change_details, expected_delta, :by) do |actual_delta| values_match?(expected_delta, actual_delta) end end
@api public Specifies the delta of the expected change.
by
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/change.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/change.rb
MIT
def by_at_least(minimum) ChangeRelatively.new(change_details, minimum, :by_at_least) do |actual_delta| actual_delta >= minimum end end
@api public Specifies a minimum delta of the expected change.
by_at_least
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/change.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/change.rb
MIT
def by_at_most(maximum) ChangeRelatively.new(change_details, maximum, :by_at_most) do |actual_delta| actual_delta <= maximum end end
@api public Specifies a maximum delta of the expected change.
by_at_most
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/change.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/change.rb
MIT
def to(value) ChangeToValue.new(change_details, value) end
@api public Specifies the new value you expect.
to
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/change.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/change.rb
MIT
def from(value) ChangeFromValue.new(change_details, value) end
@api public Specifies the original value.
from
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/change.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/change.rb
MIT
def to(value) @expected_after = value @description_suffix = " to #{description_of value}" self end
@api public Specifies the new value you expect.
to
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/change.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/change.rb
MIT
def from(value) @expected_before = value @description_suffix = " from #{description_of value}" self end
@api public Specifies the original value.
from
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/change.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/change.rb
MIT
def expected return nil unless evaluator ::RSpec::Matchers::MultiMatcherDiff.for_many_matchers(diffable_matcher_list) end
@api private @return [RSpec::Matchers::MultiMatcherDiff]
expected
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/compound.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/compound.rb
MIT
def inner_matcher_block(outer_args) return @actual if outer_args.empty? Proc.new do |*inner_args| unless inner_args.empty? raise ArgumentError, "(#{@matcher_1.description}) and " \ "(#{@matcher_2.description}) cannot be combined in a compound expectation " \ "since both matchers pass arguments to the block." end @actual.call(*outer_args) end end
Some block matchers (such as `yield_xyz`) pass args to the `expect` block. When such a matcher is used as the outer matcher, we need to forward the the args on to the `expect` block.
inner_matcher_block
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/compound.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/compound.rb
MIT
def order_block_matchers return @matcher_1, @matcher_2 unless self.class.matcher_expects_call_stack_jump?(@matcher_2) return @matcher_2, @matcher_1 unless self.class.matcher_expects_call_stack_jump?(@matcher_1) raise ArgumentError, "(#{@matcher_1.description}) and " \ "(#{@matcher_2.description}) cannot be combined in a compound expectation " \ "because they both expect a call stack jump." end
For a matcher like `raise_error` or `throw_symbol`, where the block will jump up the call stack, we need to order things so that it is the inner matcher. For example, we need it to be this: expect { expect { x += 1 raise "boom" }.to raise_error("boom") }.to change { x }.by(1) ...rather than: expect { expect { x += 1 raise "boom" }.to change { x }.by(1) }.to raise_error("boom") In the latter case, the after-block logic in the `change` matcher would never get executed because the `raise "boom"` line would jump to the `rescue` in the `raise_error` logic, so only the former case will work properly. This method figures out which matcher should be the inner matcher and which should be the outer matcher.
order_block_matchers
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/compound.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/compound.rb
MIT
def match_when_sorted? values_match?(safe_sort(expected), safe_sort(actual)) end
This cannot always work (e.g. when dealing with unsortable items, or matchers as expected items), but it's practically free compared to the slowness of the full matching algorithm, and in common cases this works, so it's worth a try.
match_when_sorted?
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/contain_exactly.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/contain_exactly.rb
MIT
def exactly(number) set_expected_count(:==, number) self end
@api public Specifies that the method is expected to match the given number of times.
exactly
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/count_expectation.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/count_expectation.rb
MIT
def at_most(number) set_expected_count(:<=, number) self end
@api public Specifies the maximum number of times the method is expected to match
at_most
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/count_expectation.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/count_expectation.rb
MIT
def at_least(number) set_expected_count(:>=, number) self end
@api public Specifies the minimum number of times the method is expected to match
at_least
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/count_expectation.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/count_expectation.rb
MIT
def with_captures(*captures) @expected_captures = captures self end
Used to specify the captures we match against @return [self]
with_captures
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/match.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/match.rb
MIT
def to_stdout @stream_capturer = CaptureStdout.new self end
@api public Tells the matcher to match against stdout. Works only when the main Ruby process prints to stdout
to_stdout
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/output.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/output.rb
MIT
def to_stderr @stream_capturer = CaptureStderr.new self end
@api public Tells the matcher to match against stderr. Works only when the main Ruby process prints to stderr
to_stderr
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/output.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/output.rb
MIT
def to_stdout_from_any_process @stream_capturer = CaptureStreamToTempfile.new("stdout", $stdout) self end
@api public Tells the matcher to match against stdout. Works when subprocesses print to stdout as well. This is significantly (~30x) slower than `to_stdout`
to_stdout_from_any_process
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/output.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/output.rb
MIT
def to_stderr_from_any_process @stream_capturer = CaptureStreamToTempfile.new("stderr", $stderr) self end
@api public Tells the matcher to match against stderr. Works when subprocesses print to stderr as well. This is significantly (~30x) slower than `to_stderr`
to_stderr_from_any_process
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/output.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/output.rb
MIT
def as_tty raise ArgumentError, '`as_tty` can only be used after `to_stdout` or `to_stderr`' unless @stream_capturer.respond_to?(:as_tty=) @stream_capturer.as_tty = true self end
@api public Tells the matcher to simulate the output stream being a TTY. This is useful to test code like `puts '...' if $stdout.tty?`.
as_tty
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/output.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/output.rb
MIT
def as_not_tty raise ArgumentError, '`as_not_tty` can only be used after `to_stdout` or `to_stderr`' unless @stream_capturer.respond_to?(:as_tty=) @stream_capturer.as_tty = false self end
@api public Tells the matcher to simulate the output stream not being a TTY. Note that that's the default behaviour if you don't call `as_tty` (since `StringIO` is not a TTY).
as_not_tty
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/output.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/output.rb
MIT
def with_message(expected_message) raise_message_already_set if @expected_message @warn_about_bare_error = false @expected_message = expected_message self end
@api public Specifies the expected error message.
with_message
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/raise_error.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/raise_error.rb
MIT
def with(n) @expected_arity = n self end
@api public Specifies the number of expected arguments. @example expect(obj).to respond_to(:message).with(3).arguments
with
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/respond_to.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/respond_to.rb
MIT
def with_keywords(*keywords) @expected_keywords = keywords self end
@api public Specifies keyword arguments, if any. @example expect(obj).to respond_to(:message).with_keywords(:color, :shape) @example with an expected number of arguments expect(obj).to respond_to(:message).with(3).arguments.and_keywords(:color, :shape)
with_keywords
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/respond_to.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/respond_to.rb
MIT
def with_any_keywords @arbitrary_keywords = true self end
@api public Specifies that the method accepts any keyword, i.e. the method has a splatted keyword parameter of the form **kw_args. @example expect(obj).to respond_to(:message).with_any_keywords
with_any_keywords
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/respond_to.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/respond_to.rb
MIT
def ignoring_method_signature_failure! @ignoring_method_signature_failure = true end
@api private Used by other matchers to suppress a check
ignoring_method_signature_failure!
ruby
rspec/rspec-expectations
lib/rspec/matchers/built_in/respond_to.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/respond_to.rb
MIT
def fail_including fail { |e| expect(e.message).to include(yield) } end
Use a normal `expect(...).to include` expectation rather than a composed matcher here. This provides better failure output because `MultipleExpectationsNotMetError#message` is lazily computed (rather than being computed in `initialize` and passed to `super`), which causes the `inspect` output of the exception to not include the message for some reason.
fail_including
ruby
rspec/rspec-expectations
spec/rspec/expectations/failure_aggregator_spec.rb
https://github.com/rspec/rspec-expectations/blob/master/spec/rspec/expectations/failure_aggregator_spec.rb
MIT
def fail_matching(message) raise_error(RSpec::Expectations::ExpectationNotMetError, /#{Regexp.escape(message)}/) end
`fail_including` uses the `include` matcher internally, and using a matcher to test itself is potentially problematic, so just for this spec file we use `fail_matching` instead, which converts to a regex instead.
fail_matching
ruby
rspec/rspec-expectations
spec/rspec/matchers/built_in/include_spec.rb
https://github.com/rspec/rspec-expectations/blob/master/spec/rspec/matchers/built_in/include_spec.rb
MIT
def underscore(camel_cased_word) word = camel_cased_word.to_s.dup word.gsub!(/::/, '/') word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2') word.gsub!(/([a-z\d])([A-Z])/, '\1_\2') word.tr!("-", "_") word.downcase! word end
Convert Foo::BarBaz to foo/bar_baz. Copied from ActiveSupport.
underscore
ruby
airbnb/ruby
rubocop-airbnb/lib/rubocop/airbnb/inflections.rb
https://github.com/airbnb/ruby/blob/master/rubocop-airbnb/lib/rubocop/airbnb/inflections.rb
MIT
def allowable_paths_for(expected_dir, options = {}) options = { allow_dir: false }.merge(options) allowable_paths = [] next_slash = expected_dir.index("/") while next_slash allowable_paths << %r{/#{expected_dir[0...next_slash]}.rb$} next_slash = expected_dir.index("/", next_slash + 1) end allowable_paths << %r{#{expected_dir}.rb$} allowable_paths << %r{/#{expected_dir}/} if options[:allow_dir] allowable_paths end
Given "foo/bar/baz", return: [ %r{/foo.rb$}, %r{/foo/bar.rb$}, %r{/foo/bar/baz.rb$}, %r{/foo/bar/baz/}, # <= only if allow_dir = true ]
allowable_paths_for
ruby
airbnb/ruby
rubocop-airbnb/lib/rubocop/airbnb/rails_autoloading.rb
https://github.com/airbnb/ruby/blob/master/rubocop-airbnb/lib/rubocop/airbnb/rails_autoloading.rb
MIT
def error_class?(node, class_or_module, const_name) return false unless class_or_module == "Class" _, base_class, *_ = *node return unless base_class base_class_name = base_class.children[1].to_s if const_name =~ /Error|Exception/ || base_class_name =~ /Error|Exception/ return true end false end
Does this node define an Error class? (Classname or base class includes the word "Error" or "Exception".)
error_class?
ruby
airbnb/ruby
rubocop-airbnb/lib/rubocop/cop/airbnb/class_or_module_declared_in_wrong_file.rb
https://github.com/airbnb/ruby/blob/master/rubocop-airbnb/lib/rubocop/cop/airbnb/class_or_module_declared_in_wrong_file.rb
MIT
def on_send(node) return unless in_factory_file?(node) return unless in_factory_or_trait?(node) add_const_offenses(node) end
Look for "attr CONST" expressions in factories or traits. In RuboCop, this is a `send` node, sending the attr method.
on_send
ruby
airbnb/ruby
rubocop-airbnb/lib/rubocop/cop/airbnb/factory_attr_references_class.rb
https://github.com/airbnb/ruby/blob/master/rubocop-airbnb/lib/rubocop/cop/airbnb/factory_attr_references_class.rb
MIT
def in_factory_or_trait?(node) return false unless node # Bail out if this IS the factory or trait node. return false unless factory_attributes(node) return false unless node.parent # Is this node in a block that was passed to the factory or trait method? if node.parent.is_a?(RuboCop::AST::Node) && node.parent.block_type? send_node = node.parent.children.first return false unless send_node return false unless send_node.send_type? # Const is referenced in the block passed to a factory or trait. return true if send_node.command?(:factory) return true if send_node.command?(:trait) # Const is a block that's nested deeper inside a factory or trait. This is what we want # developers to do. return false end in_factory_or_trait?(node.parent) end
Is this node in a factory or trait, but not inside a nested block in a factory or trait?
in_factory_or_trait?
ruby
airbnb/ruby
rubocop-airbnb/lib/rubocop/cop/airbnb/factory_attr_references_class.rb
https://github.com/airbnb/ruby/blob/master/rubocop-airbnb/lib/rubocop/cop/airbnb/factory_attr_references_class.rb
MIT
def class_node(node) node.descendants.detect do |e| e.is_a?(Parser::AST::Node) && e.pair_type? && e.children[0].children[0] == :class end end
Return the descendant node that is a hash pair (:key => value) whose key is :class.
class_node
ruby
airbnb/ruby
rubocop-airbnb/lib/rubocop/cop/airbnb/factory_class_use_string.rb
https://github.com/airbnb/ruby/blob/master/rubocop-airbnb/lib/rubocop/cop/airbnb/factory_class_use_string.rb
MIT
def includes_interpolation?(args) !args.first.nil? && args.first.type == :dstr && args.first.each_child_node.any? { |child| child.type != :str } end
Return true if the first arg is a :dstr that has non-:str components
includes_interpolation?
ruby
airbnb/ruby
rubocop-airbnb/lib/rubocop/cop/airbnb/risky_activerecord_invocation.rb
https://github.com/airbnb/ruby/blob/master/rubocop-airbnb/lib/rubocop/cop/airbnb/risky_activerecord_invocation.rb
MIT
def validate_and_consume_otp!(code, options = {}) otp_secret = options[:otp_secret] || self.otp_secret return false unless code.present? && otp_secret.present? totp = otp(otp_secret) if self.consumed_timestep # reconstruct the timestamp of the last consumed timestep after_timestamp = self.consumed_timestep * totp.interval end timestamp = totp.verify(code.gsub(/\s+/, ""), drift_behind: self.class.otp_allowed_drift, drift_ahead: self.class.otp_allowed_drift, after: after_timestamp) return consume_otp!(totp, timestamp) if timestamp false end
This defaults to the model's otp_secret If this hasn't been generated yet, pass a secret as an option
validate_and_consume_otp!
ruby
devise-two-factor/devise-two-factor
lib/devise_two_factor/models/two_factor_authenticatable.rb
https://github.com/devise-two-factor/devise-two-factor/blob/master/lib/devise_two_factor/models/two_factor_authenticatable.rb
MIT
def consume_otp!(otp, timestamp) timestep = timestamp / otp.interval if self.consumed_timestep != timestep self.consumed_timestep = timestep save!(validate: false) return true end false end
An OTP cannot be used more than once in a given timestep Storing timestep of last valid OTP is sufficient to satisfy this requirement
consume_otp!
ruby
devise-two-factor/devise-two-factor
lib/devise_two_factor/models/two_factor_authenticatable.rb
https://github.com/devise-two-factor/devise-two-factor/blob/master/lib/devise_two_factor/models/two_factor_authenticatable.rb
MIT
def splattable_encrypted_attr_options return {} if otp_encrypted_attribute_options.nil? otp_encrypted_attribute_options end
Return value will be splatted with ** so return a version of the encrypted attribute options which is always a Hash. @return [Hash]
splattable_encrypted_attr_options
ruby
devise-two-factor/devise-two-factor
lib/devise_two_factor/models/two_factor_authenticatable.rb
https://github.com/devise-two-factor/devise-two-factor/blob/master/lib/devise_two_factor/models/two_factor_authenticatable.rb
MIT
def generate_otp_backup_codes! codes = [] number_of_codes = self.class.otp_number_of_backup_codes code_length = self.class.otp_backup_code_length number_of_codes.times do codes << SecureRandom.hex(code_length) end hashed_codes = codes.map { |code| Devise::Encryptor.digest(self.class, code) } self.otp_backup_codes = hashed_codes codes end
1) Invalidates all existing backup codes 2) Generates otp_number_of_backup_codes backup codes 3) Stores the hashed backup codes in the database 4) Returns a plaintext array of the generated backup codes
generate_otp_backup_codes!
ruby
devise-two-factor/devise-two-factor
lib/devise_two_factor/models/two_factor_backupable.rb
https://github.com/devise-two-factor/devise-two-factor/blob/master/lib/devise_two_factor/models/two_factor_backupable.rb
MIT
def invalidate_otp_backup_code!(code) codes = self.otp_backup_codes || [] codes.each do |backup_code| next unless Devise::Encryptor.compare(self.class, backup_code, code) codes.delete(backup_code) self.otp_backup_codes = codes save!(validate: false) return true end false end
Returns true and invalidates the given code if that code is a valid backup code.
invalidate_otp_backup_code!
ruby
devise-two-factor/devise-two-factor
lib/devise_two_factor/models/two_factor_backupable.rb
https://github.com/devise-two-factor/devise-two-factor/blob/master/lib/devise_two_factor/models/two_factor_backupable.rb
MIT
def setup_backtrace_cleaner cleaner = Rails::BacktraceCleaner.new remove_filters_and_silencers cleaner cleaner.instance_variable_set :@root, Rails.root.to_s if cleaner.instance_variable_get(:@root) == '/' case ActiveRecordQueryTrace.level when :app cleaner.add_silencer { |line| line !~ rails_root_regexp } when :rails cleaner.add_silencer { |line| line =~ rails_root_regexp } end cleaner end
The following code creates a brand new BacktraceCleaner just for the use of this Gem avoiding the dealing with Rails.backtrace_cleaner
setup_backtrace_cleaner
ruby
brunofacca/active-record-query-trace
lib/active_record_query_trace.rb
https://github.com/brunofacca/active-record-query-trace/blob/master/lib/active_record_query_trace.rb
MIT
def rails_root_regexp @rails_root_regexp ||= %r{#{Regexp.escape(Rails.root.to_s)}(?!/vendor)} end
This cannot be set in a constant as Rails.root is not yet available when this file is loaded.
rails_root_regexp
ruby
brunofacca/active-record-query-trace
lib/active_record_query_trace.rb
https://github.com/brunofacca/active-record-query-trace/blob/master/lib/active_record_query_trace.rb
MIT
def display_backtrace?(payload) ActiveRecordQueryTrace.enabled \ && !transaction_begin_or_commit_query?(payload) \ && !schema_query?(payload) \ && !cached_query?(payload) \ && !(ActiveRecordQueryTrace.suppress_logging_of_db_reads && db_read_query?(payload)) \ && display_backtrace_for_query_type?(payload) end
TODO: refactor and remove rubocop:disable comments.
display_backtrace?
ruby
brunofacca/active-record-query-trace
lib/active_record_query_trace.rb
https://github.com/brunofacca/active-record-query-trace/blob/master/lib/active_record_query_trace.rb
MIT
def lines_to_display(full_trace) ActiveRecordQueryTrace.lines.zero? ? full_trace : full_trace.first(ActiveRecordQueryTrace.lines) end
Must be called after the backtrace cleaner.
lines_to_display
ruby
brunofacca/active-record-query-trace
lib/active_record_query_trace.rb
https://github.com/brunofacca/active-record-query-trace/blob/master/lib/active_record_query_trace.rb
MIT
def colorize_text(text) return text unless ActiveRecordQueryTrace.colorize "\e[#{color_code}m#{text}\e[0m" end
rubocop:enable Metrics/MethodLength Allow query to be colorized in the terminal
colorize_text
ruby
brunofacca/active-record-query-trace
lib/active_record_query_trace.rb
https://github.com/brunofacca/active-record-query-trace/blob/master/lib/active_record_query_trace.rb
MIT
def define_matcher(resource_name) matchers[resource_name.to_sym] = Proc.new do |identity| find_resource(resource_name, identity) end self end
Defines a new runner method on the Chef runner. @param [Symbol] resource_name the name of the resource to define a method @return [self]
define_matcher
ruby
chefspec/chefspec
lib/chefspec.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec.rb
MIT
def root @root ||= Pathname.new(File.expand_path("..", __dir__)) end
The source root of the ChefSpec gem. This is useful when requiring files that are relative to the root of the project. @return [Pathname]
root
ruby
chefspec/chefspec
lib/chefspec.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec.rb
MIT
def matchers @matchers ||= {} end
The list of custom defined matchers. @return [Hash<String, Proc>]
matchers
ruby
chefspec/chefspec
lib/chefspec.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec.rb
MIT
def setup! # Get the list of Berkshelf options opts = RSpec.configuration.berkshelf_options unless opts.is_a?(Hash) raise InvalidBerkshelfOptions(value: opts.inspect) end berksfile = ::Berkshelf::Berksfile.from_options(opts) # Grab a handle to tmpdir, since Berkshelf 2 modifies it a bit tmpdir = File.join(@tmpdir, "cookbooks") ::Berkshelf.ui.mute do if ::Berkshelf::Berksfile.method_defined?(:vendor) # Berkshelf 3.0 requires the directory to not exist FileUtils.rm_rf(tmpdir) berksfile.vendor(tmpdir) else berksfile.install(path: tmpdir) end end filter = Coverage::BerkshelfFilter.new(berksfile) Coverage.add_filter(filter) ::RSpec.configure { |config| config.cookbook_path = tmpdir } end
Setup and install the necessary dependencies in the temporary directory.
setup!
ruby
chefspec/chefspec
lib/chefspec/berkshelf.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/berkshelf.rb
MIT
def teardown! FileUtils.rm_rf(@tmpdir) if File.exist?(@tmpdir) end
Destroy the installed Berkshelf at the temporary directory.
teardown!
ruby
chefspec/chefspec
lib/chefspec/berkshelf.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/berkshelf.rb
MIT
def start!(&block) warn("ChefSpec's coverage reporting is deprecated and will be removed in a future version") instance_eval(&block) if block at_exit { ChefSpec::Coverage.report! } end
Start the coverage reporting analysis. This method also adds the the +at_exit+ handler for printing the coverage report.
start!
ruby
chefspec/chefspec
lib/chefspec/coverage.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/coverage.rb
MIT
def add_filter(filter = nil, &block) id = "#{filter.inspect}/#{block.inspect}".hash @filters[id] = if filter.is_a?(Filter) filter elsif filter.is_a?(String) StringFilter.new(filter) elsif filter.is_a?(Regexp) RegexpFilter.new(filter) elsif block BlockFilter.new(block) else raise ArgumentError, "Please specify either a string, " \ "filter, or block to filter source files with!" end true end
Add a filter to the coverage analysis. @param [Filter, String, Regexp] filter the filter to add @param [Proc] block the block to use as a filter @return [true]
add_filter
ruby
chefspec/chefspec
lib/chefspec/coverage.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/coverage.rb
MIT
def add_output(&block) @outputs << block end
Add an output to send the coverage results to. @param [Proc] block the block to use as the output @return [true]
add_output
ruby
chefspec/chefspec
lib/chefspec/coverage.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/coverage.rb
MIT
def set_template(file = "human.erb") @template = [ ChefSpec.root.join("templates", "coverage", file), File.expand_path(file, Dir.pwd), ].find { |f| File.exist?(f) } raise Error::TemplateNotFound.new(path: file) unless @template end
Change the template for reporting of converage analysis. @param [string] path The template file to use for the output of the report @return [true]
set_template
ruby
chefspec/chefspec
lib/chefspec/coverage.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/coverage.rb
MIT
def add(resource) if !exists?(resource) && !filtered?(resource) @collection[resource.to_s] = ResourceWrapper.new(resource) end end
Add a resource to the resource collection. Only new resources are added and only resources that match the given filter are covered (which is * by default). @param [Chef::Resource] resource
add
ruby
chefspec/chefspec
lib/chefspec/coverage.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/coverage.rb
MIT
def cover!(resource) wrapper = find(resource) wrapper.touch! if wrapper end
Called when a resource is matched to indicate it has been tested. @param [Chef::Resource] resource
cover!
ruby
chefspec/chefspec
lib/chefspec/coverage.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/coverage.rb
MIT
def filtered?(resource) filters.any? { |_, filter| filter.matches?(resource) } end
Called to check if a resource belongs to a cookbook from the specified directories. @param [Chef::Resource] resource
filtered?
ruby
chefspec/chefspec
lib/chefspec/coverage.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/coverage.rb
MIT
def report! # Borrowed from simplecov#41 # # If an exception is thrown that isn't a "SystemExit", we need to capture # that error and re-raise. if $! exit_status = $!.is_a?(SystemExit) ? $!.status : EXIT_FAILURE else exit_status = EXIT_SUCCESS end report = {}.tap do |h| h[:total] = @collection.size h[:touched] = @collection.count { |_, resource| resource.touched? } h[:coverage] = ((h[:touched] / h[:total].to_f) * 100).round(2) end report[:untouched_resources] = @collection.collect do |_, resource| resource unless resource.touched? end.compact report[:all_resources] = @collection.values @outputs.each do |block| instance_exec(report, &block) end # Ensure we exit correctly (#351) Kernel.exit(exit_status) if exit_status && exit_status > 0 end
Generate a coverage report. This report **must** be generated +at_exit+ or else the entire resource collection may not be complete! @example Generating a report ChefSpec::Coverage.report!
report!
ruby
chefspec/chefspec
lib/chefspec/coverage.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/coverage.rb
MIT
def deprecated(*messages) messages.each do |message| calling_spec = caller.find { |line| line =~ %r{(/spec)|(_spec\.rb)} } if calling_spec calling_spec = "spec/" + calling_spec.split("/spec/").last warn "[DEPRECATION] #{message} (called from #{calling_spec})" else warn "[DEPRECATION] #{message}" end end end
Kernel extension to print deprecation notices. @example printing a deprecation warning deprecated 'no longer in use' #=> "[DEPRECATION] no longer in use" @param [Array<String>] messages
deprecated
ruby
chefspec/chefspec
lib/chefspec/deprecations.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/deprecations.rb
MIT
def registration_failed(node_name, exception, config) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.registration_failed(node_name, exception, config) display_error(description) end end
Failed to register this client with the server.
registration_failed
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def node_load_failed(node_name, exception, config) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.node_load_failed(node_name, exception, config) display_error(description) end end
Failed to load node data from the server
node_load_failed
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def cookbook_resolution_failed(expanded_run_list, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.cookbook_resolution_failed(expanded_run_list, exception) display_error(description) end end
Called when there is an error getting the cookbook collection from the server.
cookbook_resolution_failed
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def cookbook_sync_failed(cookbooks, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.cookbook_sync_failed(cookbooks, exception) display_error(description) end end
Called when an error occurs during cookbook sync
cookbook_sync_failed
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def library_file_load_failed(path, exception) file_load_failed(path, exception) end
Called when a library file has an error on load.
library_file_load_failed
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def lwrp_file_load_failed(path, exception) file_load_failed(path, exception) end
Called after a LWR or LWP file errors on load
lwrp_file_load_failed
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def attribute_file_load_failed(path, exception) file_load_failed(path, exception) end
Called when an attribute file fails to load.
attribute_file_load_failed
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def definition_file_load_failed(path, exception) file_load_failed(path, exception) end
Called when a resource definition file fails to load
definition_file_load_failed
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def recipe_file_load_failed(path, exception) file_load_failed(path, exception) end
Called after a recipe file fails to load
recipe_file_load_failed
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def recipe_not_found(exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.file_load_failed(nil, exception) display_error(description) end end
Called when a recipe cannot be resolved
recipe_not_found
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def resource_failed(resource, action, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.resource_failed(resource, action, exception) display_error(description) end end
Called when a resource fails and will not be retried.
resource_failed
ruby
chefspec/chefspec
lib/chefspec/formatter.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/formatter.rb
MIT
def setup! env = ::Librarian::Chef::Environment.new(project_path: Dir.pwd) @originalpath, env.config_db.local["path"] = env.config_db.local["path"], @tmpdir ::Librarian::Action::Resolve.new(env).run ::Librarian::Action::Install.new(env).run ::RSpec.configure { |config| config.cookbook_path = @tmpdir } end
Setup and install the necessary dependencies in the temporary directory.
setup!
ruby
chefspec/chefspec
lib/chefspec/librarian.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/librarian.rb
MIT
def teardown! env = ::Librarian::Chef::Environment.new(project_path: Dir.pwd) env.config_db.local["path"] = @originalpath FileUtils.rm_rf(@tmpdir) if File.exist?(@tmpdir) end
Remove the temporary directory and restore the librarian-chef cookbook path.
teardown!
ruby
chefspec/chefspec
lib/chefspec/librarian.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/librarian.rb
MIT
def setup! policyfile_path = RSpec.configuration.policyfile_path if policyfile_path.nil? policyfile_path = File.join(Dir.pwd, "Policyfile.rb") end Chef::WorkstationConfigLoader.new(nil).load installer = ChefCLI::PolicyfileServices::Install.new( policyfile: policyfile_path, ui: ChefCLI::UI.null, config: Chef::Config ) installer.run exporter = ChefCLI::PolicyfileServices::ExportRepo.new( policyfile: policyfile_path, export_dir: @tmpdir ) FileUtils.rm_rf(@tmpdir) exporter.run ::RSpec.configure do |config| config.cookbook_path = [ File.join(@tmpdir, "cookbooks"), File.join(@tmpdir, "cookbook_artifacts"), ] end end
Setup and install the necessary dependencies in the temporary directory
setup!
ruby
chefspec/chefspec
lib/chefspec/policyfile.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/policyfile.rb
MIT
def initialize(chef_run, resource) @chef_run = chef_run @resource = resource end
Create a new Renderer for the given Chef run and resource. @param [Chef::Runner] chef_run the Chef run containing the resources @param [Chef::Resource] resource the resource to render content from
initialize
ruby
chefspec/chefspec
lib/chefspec/renderer.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/renderer.rb
MIT
def content case resource_name(resource) when :template content_from_template(chef_run, resource) when :file content_from_file(chef_run, resource) when :cookbook_file content_from_cookbook_file(chef_run, resource) else nil end end
The content of the resource (this method delegates to the) various private rendering methods. @return [String, nil] the contents of the file as a string, or nil if the resource does not contain or respond to a content renderer.
content
ruby
chefspec/chefspec
lib/chefspec/renderer.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/renderer.rb
MIT
def content_from_template(chef_run, template) cookbook_name = template.cookbook || template.cookbook_name template_location = cookbook_collection(chef_run.node)[cookbook_name].preferred_filename_on_disk_location(chef_run.node, :templates, template.source) if Chef::Mixin::Template.const_defined?(:TemplateContext) # Chef 11+ template_context = Chef::Mixin::Template::TemplateContext.new([]) template_context.update({ node: chef_run.node, template_finder: template_finder(chef_run, cookbook_name), }.merge(template.variables)) if template.respond_to?(:helper_modules) # Chef 11.4+ template_context._extend_modules(template.helper_modules) end template_context.render_template(template_location) else template.provider.new(template, chef_run.run_context).send(:render_with_context, template_location) do |file| File.read(file.path) end end end
Compute the contents of a template using Chef's templating logic. @param [Chef::RunContext] chef_run the run context for the node @param [Chef::Provider::Template] template the template resource @return [String]
content_from_template
ruby
chefspec/chefspec
lib/chefspec/renderer.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/renderer.rb
MIT
def content_from_cookbook_file(chef_run, cookbook_file) cookbook_name = cookbook_file.cookbook || cookbook_file.cookbook_name cookbook = cookbook_collection(chef_run.node)[cookbook_name] File.read(cookbook.preferred_filename_on_disk_location(chef_run.node, :files, cookbook_file.source)) end
Get the contents of a cookbook file using Chef. @param [Chef::RunContext] chef_run the run context for the node @param [Chef::Provider::CookbookFile] cookbook_file the file resource
content_from_cookbook_file
ruby
chefspec/chefspec
lib/chefspec/renderer.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/renderer.rb
MIT
def cookbook_collection(node) if chef_run.respond_to?(:run_context) chef_run.run_context.cookbook_collection # Chef 11.8+ elsif node.respond_to?(:run_context) node.run_context.cookbook_collection # Chef 11+ else node.cookbook_collection # Chef 10 end end
The cookbook collection for the current Chef run context. Handles the differing cases between Chef 10 and Chef 11. @param [Chef::Node] node the Chef node to get the cookbook collection from @return [Array<Chef::Cookbook>]
cookbook_collection
ruby
chefspec/chefspec
lib/chefspec/renderer.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/renderer.rb
MIT
def template_finder(chef_run, cookbook_name) if Chef::Provider.const_defined?(:TemplateFinder) # Chef 11+ Chef::Provider::TemplateFinder.new(chef_run.run_context, cookbook_name, chef_run.node) else nil end end
Return a new instance of the TemplateFinder if we are running on Chef 11. @param [Chef::RunContext] chef_run the run context for the noe @param [String] cookbook_name the name of the cookbook @return [Chef::Provider::TemplateFinder, nil]
template_finder
ruby
chefspec/chefspec
lib/chefspec/renderer.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/renderer.rb
MIT
def create_data_bag(name, data = {}) load_data(name, "data", data) end
Create a new data_bag on the Chef Server. This overrides the method created by {entity} @param [String] name the name of the data bag @param [Hash] data the data to load into the data bag
create_data_bag
ruby
chefspec/chefspec
lib/chefspec/server_methods.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/server_methods.rb
MIT
def load_data(name, key, data = {}) ChefSpec::ZeroServer.load_data(name, key, data) end
Shortcut method for loading data into Chef Zero. @param [String] name the name or id of the item to load @param [String, Symbol] key the key to load @param [Hash] data the data for the object, which will be converted to JSON and uploaded to the server
load_data
ruby
chefspec/chefspec
lib/chefspec/server_methods.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/server_methods.rb
MIT
def get(*args) args.unshift("organizations", "chef") if args.size == 3 server.data_store.list(args) else server.data_store.get(args) end end
Get the path to an item in the data store.
get
ruby
chefspec/chefspec
lib/chefspec/server_methods.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/server_methods.rb
MIT
def client_key tmp = Dir.mktmpdir path = File.join(tmp, "client.pem") File.open(path, "wb") { |f| f.write(ChefZero::PRIVATE_KEY) } at_exit { FileUtils.rm_rf(tmp) } path end
The path to the insecure Chef Zero private key on disk. Because Chef requires the path to a file instead of the contents of the key (why), this method dynamically writes the +ChefZero::PRIVATE_KEY+ to disk and then returns that path. @return [String] the path to the client key on disk
client_key
ruby
chefspec/chefspec
lib/chefspec/server_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/server_runner.rb
MIT
def initialize(options = {}) @options = with_default_options(options) apply_chef_config! yield node if block_given? end
Instantiate a new SoloRunner to run examples with. @example Instantiate a new Runner ChefSpec::SoloRunner.new @example Specifying the platform and version ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '18.04') @example Specifying the cookbook path ChefSpec::SoloRunner.new(cookbook_path: ['/cookbooks']) @example Specifying the log level ChefSpec::SoloRunner.new(log_level: :info) @param [Hash] options The options for the new runner @option options [Symbol] :log_level The log level to use (default is :warn) @option options [String] :platform The platform to load Ohai attributes from (must be present in fauxhai) @option options [String] :version The version of the platform to load Ohai attributes from (must be present in fauxhai) @option options [String] :path Path of a json file that will be passed to fauxhai as :path option @option options [Array<String>] :step_into The list of LWRPs to evaluate @option options String] :file_cache_path File caching path, if absent ChefSpec will use a temporary directory generated on the fly @yield [node] Configuration block for Chef::Node
initialize
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def converge(*recipe_names) # Re-apply the Chef config before converging in case something else # called Config.reset too. apply_chef_config! @converging = false node.run_list.reset! recipe_names.each { |recipe_name| node.run_list.add(recipe_name) } return self if dry_run? # Expand the run_list expand_run_list! # Merge in provided node attributes. Default and override use the role_ # levels so they win over the relevant bits from cookbooks since otherwise # they would not and that would be confusing. node.attributes.role_default = Chef::Mixin::DeepMerge.merge(node.attributes.role_default, options[:default_attributes]) if options[:default_attributes] node.attributes.normal = Chef::Mixin::DeepMerge.merge(node.attributes.normal, options[:normal_attributes]) if options[:normal_attributes] node.attributes.role_override = Chef::Mixin::DeepMerge.merge(node.attributes.role_override, options[:override_attributes]) if options[:override_attributes] node.attributes.automatic = Chef::Mixin::DeepMerge.merge(node.attributes.automatic, options[:automatic_attributes]) if options[:automatic_attributes] # Setup the run_context, rescuing the exception that happens when a # resource is not defined on a particular platform begin @run_context = client.setup_run_context rescue Chef::Exceptions::NoSuchResourceType => e raise Error::MayNeedToSpecifyPlatform.new(original_error: e.message) end # Allow stubbing/mocking after the cookbook has been compiled but before the converge yield node if block_given? @converging = true converge_val = @client.converge(@run_context) if converge_val.is_a?(Exception) raise converge_val end self end
Execute the given `run_list` on the node, without actually converging the node. Each time {#converge} is called, the `run_list` is reset to the new value (it is **not** additive). @example Converging a single recipe chef_run.converge('example::default') @example Converging multiple recipes chef_run.converge('example::default', 'example::secondary') @param [Array] recipe_names The names of the recipe or recipes to converge @return [ChefSpec::SoloRunner] A reference to the calling Runner (for chaining purposes)
converge
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def converge_block(&block) converge do recipe = Chef::Recipe.new(cookbook_name, "_test", run_context) recipe.instance_exec(&block) end end
Execute a block of recipe code. @param [Proc] block A block containing Chef recipe code @return [ChefSpec::SoloRunner]
converge_block
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def preload! # Flag to disable preloading for situations where it doesn't make sense. return if ENV["CHEFSPEC_NO_PRELOAD"] begin old_preload = $CHEFSPEC_PRELOAD $CHEFSPEC_PRELOAD = true converge("recipe[#{cookbook_name}]") node.run_list.reset! ensure $CHEFSPEC_PRELOAD = old_preload end end
Run a static preload of the cookbook under test. This will load libraries and resources, but not attributes or recipes. @return [void]
preload!
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def node runner = self @node ||= begin apply_chef_config! client.build_node.tap do |node| node.define_singleton_method(:runner) { runner } end end end
The +Chef::Node+ corresponding to this Runner. @return [Chef::Node]
node
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT