Class: ConvenientService::RSpec::Matchers::Classes::CacheItsValue

Inherits:
Object
  • Object
show all
Defined in:
lib/convenient_service/rspec/matchers/classes/cache_its_value.rb

Instance Method Summary collapse

Instance Method Details

#descriptionObject



47
48
49
# File 'lib/convenient_service/rspec/matchers/classes/cache_its_value.rb', line 47

def description
  "cache its value"
end

#failure_messageObject



51
52
53
# File 'lib/convenient_service/rspec/matchers/classes/cache_its_value.rb', line 51

def failure_message
  "expected #{printable_block_expectation} to cache its value"
end

#failure_message_when_negatedObject



55
56
57
# File 'lib/convenient_service/rspec/matchers/classes/cache_its_value.rb', line 55

def failure_message_when_negated
  "expected #{printable_block_expectation} NOT to cache its value"
end

#matches?(block_expectation) ⇒ Boolean

Note:

cache_its_value may lead to false positives.

Note:

cache_its_value calls the expect block twice to check its return values object ids.

Examples:

False positive spec.


let(:command_result) { command.call }

specify do
  # bad - `command_result` is already cached(memoized) by `let`. That is why `cache_its_value` is always satisfied.
  expect { command_result }.to cache_its_value
end

Correct spec.


specify do
  # good - `command.call` is recalculated every time `expect` block is invoked.
  expect { command.call }.to cache_its_value
end

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
41
# File 'lib/convenient_service/rspec/matchers/classes/cache_its_value.rb', line 33

def matches?(block_expectation)
  @block_expectation = block_expectation

  ##
  # NOTE: Avoid comparing object ids. Prefer `equal?`.
  # - https://bugs.ruby-lang.org/issues/15408
  #
  block_expectation.call.equal?(block_expectation.call)
end

#printable_block_expectationObject

NOTE: An example of how RSpec extracts block source, but they marked it as private.
https://github.com/rspec/rspec-expectations/blob/311aaf245f2c5493572bf683b8c441cb5f7e44c8/lib/rspec/matchers/built_in/change.rb#L437

TODO: printable_block_expectation when method_source is available.
https://github.com/banister/method_source

def printable_block_expectation
@printable_block_expectation ||= block_expectation.source
end



70
71
72
# File 'lib/convenient_service/rspec/matchers/classes/cache_its_value.rb', line 70

def printable_block_expectation
  @printable_block_expectation ||= "{ ... }"
end

#supports_block_expectations?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/convenient_service/rspec/matchers/classes/cache_its_value.rb', line 43

def supports_block_expectations?
  true
end