active_model_serializers/test/generators/serializer_generator_test.rb
Dave Gynn 94db22c1e0 Only load generators when needed
- use hook_for to hook in the serializer and remove load_generators
- move generators so they can be found by rails
- move to_prepare block to railtie config

This commit improves the way the generators are loaded and how
they extend the resource generator.

* The initializer block has been changed to a `generator` block which is only executed when generators are needed.
* The call to `app.load_generators` has been removed. There is no need to load *all* generators.
* The `resource_override.rb` has been changed to use `hook_for` to extend the resource generator.
* The directory for the generators has been moved to match the way Rails looks to load generators.

With `hook_for` it would now be possible for a user to pass `--no-serializer` to skip that option.
The `--serialize` option also now shows up in the generator help with `rails g resource --help`.

These changes follow the way the Draper gem extends the `controller` generator.
2016-01-15 01:52:27 -06:00

58 lines
2.0 KiB
Ruby

require 'test_helper'
require 'generators/rails/resource_override'
require 'generators/rails/serializer_generator'
class SerializerGeneratorTest < Rails::Generators::TestCase
destination File.expand_path('../../../tmp/generators', __FILE__)
setup :prepare_destination
tests Rails::Generators::SerializerGenerator
arguments %w(account name:string description:text business:references)
def test_generates_a_serializer
run_generator
assert_file 'app/serializers/account_serializer.rb', /class AccountSerializer < ActiveModel::Serializer/
end
def test_generates_a_namespaced_serializer
run_generator ['admin/account']
assert_file 'app/serializers/admin/account_serializer.rb', /class Admin::AccountSerializer < ActiveModel::Serializer/
end
def test_uses_application_serializer_if_one_exists
Object.const_set(:ApplicationSerializer, Class.new)
run_generator
assert_file 'app/serializers/account_serializer.rb', /class AccountSerializer < ApplicationSerializer/
ensure
Object.send :remove_const, :ApplicationSerializer
end
def test_uses_given_parent
Object.const_set(:ApplicationSerializer, Class.new)
run_generator ['Account', '--parent=MySerializer']
assert_file 'app/serializers/account_serializer.rb', /class AccountSerializer < MySerializer/
ensure
Object.send :remove_const, :ApplicationSerializer
end
def test_generates_attributes_and_associations
run_generator
assert_file 'app/serializers/account_serializer.rb' do |serializer|
assert_match(/^ attributes :id, :name, :description$/, serializer)
assert_match(/^ has_one :business$/, serializer)
assert_match(/^end\n*\z/, serializer)
end
end
def test_with_no_attributes_does_not_add_extra_space
run_generator ['account']
assert_file 'app/serializers/account_serializer.rb' do |content|
if RUBY_PLATFORM =~ /mingw/
assert_no_match(/\r\n\r\nend/, content)
else
assert_no_match(/\n\nend/, content)
end
end
end
end