gem - RSpec: How can I stub a method on an object, before instantiation, without having to stub all the rest? -
i writing gem rails, includes generator create model. under circumstances, generator supposed call itself, , uses generate
method this. works fine when using it.
i using rspec 3.2 generator_spec
try , test functionality, being gem, when gets generate
call, complains rails doesn't exist:
/path/to/ruby: no such file or directory -- bin/rails (loaderror)
so have been trying stub generator#generate
method make same thing run_generator
in spec, before run_generator
calls call generate
in middle of them. however, of potential solutions, have run problems.
outright overriding class - can't use spec method.
class generator def generate(*args) run_generator args[1..-1] end end
this raises undefined method 'run_generator'
. not surprising.
using partial double - instantiated late.
allow(generator).to receive(:generate) { |*args| run_generator args[1..-1] }
this perfect, run_generator
calls class method behind scenes, generator
in question doesn't exist yet.
using instance double - disallows other methods.
recursible = instance_double(generator) allow(recursible).to receive(:generate) { |*args| run_generator args[1..-1] } test_case_instance.generator_class = recursible
however, using double requires stub all methods on going used - , rest calling original implementations. seems difficult , unnecessary. there way round it?
taryn east ended giving me vital clue: needed full-blown rails app in test directory.
unfortunately, generator_spec
's prepare_destination
method blows target directory away, here's ended with:
it 'the test' system "rails new #{destination_root} -bfq" # no bundling, force overwrite, quiet file.write "#{destination_root}/gemfile", "gem '#{file.basename dir.pwd}', path: '#{dir.pwd}'", mode: 'a' system "cd #{destination_root} && bundle install --quiet" # ... continue test before