问题描述:

I have a rails generator I want to make that, amongst other things, will run some scaffolds based off of a yaml file:

class MyGenerator < Rails::Generators::Base

...

def run_scaffolds

...

invoke 'scaffold', fields

...

end

end

I'm invoking the scaffold generator as described here.

The problem is if I try and run this in a unit test:

class ScaffoldTest < Rails::Generators::TestCase

tests MyGenerator

destination File.expand_path("../tmp", File.dirname(__FILE__))

setup :prepare_destination

test "run scaffolds" do

run_generator ["example_file.yaml"]

# doesn't get to here

end

end

I end up with an error:

Errno::ENOENT: No such file or directory - .../tmp/config/routes.rb

This is because there is no Rails app in the tmp directory. My question is how can I possibly test this generator if it can't be executed without a rails app? Surely I shouldn't I be creating a new rails app in the tmp folder everytime I run my tests?

网友答案:

I've decided to stub out the call to the generator using mocha:

Rails::Generator.stubs(:invoke)
run_generator ["example_file.yaml"]

I chose this solution because it let's me verify that the code is calling the generator with the correct arguments and it doesn't require that I actually run the generator in a real rails app.

相关阅读:
Top