Skip to content

Commit

Permalink
add example to mimic #42
Browse files Browse the repository at this point in the history
  • Loading branch information
moktin committed Apr 4, 2014
1 parent f3274cd commit cbf540a
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
19 changes: 19 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,25 @@ null_io.foobar # =>
# <null:IO>:NullIO (NoMethodError)
```

It is also possible to give `mimic` the `example` option to stub methods of a specific instance.
It can be useful when the instance define its own methods.

```ruby
require "naught"
require "logging"
log = Logging.logger["test"]
log.info
NullLog = Naught.build do |config|
config.mimic log.class, example: log
end
null_log = NullLog.new
null_log.info # => nil
```

There is also `impersonate` which takes `mimic` one step further. The
generated null class will be derived from the impersonated class. This
is handy when refitting legacy code that contains type checks.
Expand Down
11 changes: 9 additions & 2 deletions lib/naught/null_class_builder/commands/mimic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ module Naught
class NullClassBuilder
module Commands
class Mimic < Naught::NullClassBuilder::Command
attr_reader :class_to_mimic, :include_super
attr_reader :class_to_mimic, :include_super, :instance_to_mimic

def initialize(builder, class_to_mimic, options = {})
super(builder)

@class_to_mimic = class_to_mimic
@include_super = options.fetch(:include_super) { true }
@instance_to_mimic = options.fetch(:example) { nil }

builder.base_class = root_class_of(class_to_mimic)
builder.inspect_proc = lambda { "<null:#{class_to_mimic}>" }
Expand All @@ -33,7 +34,13 @@ def root_class_of(klass)
end

def methods_to_stub
class_to_mimic.instance_methods(include_super) - Object.instance_methods
methods_to_mimic = if instance_to_mimic
instance_to_mimic.public_methods(include_super)
else
class_to_mimic.instance_methods(include_super)
end

methods_to_mimic - Object.instance_methods
end
end
end
Expand Down
14 changes: 14 additions & 0 deletions spec/mimic_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,20 @@ def notify_of_overdue_books(titles)
expect(null).to_not respond_to(:login)
end
end

describe 'with an instance as example' do

let(:mimic_class) do
Naught.build do |b|
b.mimic User, :example => LibraryPatron.new
end
end

it 'responds to method defined on the example instance' do
expect(null).to respond_to(:member?)
end
end

end

describe 'using mimic with black_hole' do
Expand Down

0 comments on commit cbf540a

Please sign in to comment.