File tree Expand file tree Collapse file tree 2 files changed +51
-1
lines changed
lib/generators/jsonapi/serializable Expand file tree Collapse file tree 2 files changed +51
-1
lines changed Original file line number Diff line number Diff line change @@ -6,13 +6,21 @@ class SerializableGenerator < ::Rails::Generators::NamedBase
66 # TODO(beauby): Implement versioning.
77
88 def copy_serializable_file
9+ fail "#{ class_name } model not found." unless model_exists?
10+
911 template 'serializable.rb.erb' ,
1012 File . join ( 'app/serializable' , class_path ,
1113 "#{ serializable_file_name } .rb" )
1214 end
1315
1416 private
1517
18+ def model_exists?
19+ Rails . application . eager_load!
20+ models = ApplicationRecord . descendants . map ( &:name )
21+ !!models . find { |model_name | model_name == class_name }
22+ end
23+
1624 def serializable_file_name
1725 "serializable_#{ file_name } "
1826 end
@@ -22,7 +30,6 @@ def serializable_class_name
2230 end
2331
2432 def model_klass
25- # TODO(beauby): Ensure the model class exists.
2633 class_name . safe_constantize
2734 end
2835
Original file line number Diff line number Diff line change 1+ require 'rails_helper'
2+ require 'rails/generators'
3+ require_relative File . expand_path ( "../../lib/generators/jsonapi/serializable/serializable_generator.rb" , __FILE__ )
4+
5+ describe Jsonapi ::SerializableGenerator do
6+ with_model :User , superclass : ApplicationRecord , scope : :all do
7+ table do |t |
8+ t . string :name
9+ t . string :email
10+ end
11+ end
12+
13+ before do
14+ @test_case = Rails ::Generators ::TestCase . new ( :fake_test_case )
15+ @test_case . class . tests ( described_class )
16+ @test_case . class . destination ( File . expand_path ( "../tmp" , File . dirname ( __FILE__ ) ) )
17+ @test_case . send ( :prepare_destination )
18+ end
19+
20+ context "passing an existent model" do
21+ let ( :model_name ) { "User" }
22+
23+ it "creates a serializable resource" do
24+ @test_case . assert_no_file "app/serializable/serializable_user.rb"
25+ @test_case . run_generator ( [ model_name ] )
26+ @test_case . assert_file "app/serializable/serializable_user.rb" , /SerializableUser/
27+ end
28+ end
29+
30+ context "passing an nonexistent model" do
31+ let ( :model_name ) { "Dummy" }
32+
33+ it "raises an error" do
34+ expect { @test_case . run_generator ( [ model_name ] ) } . to raise_error ( RuntimeError , "Dummy model not found." )
35+ end
36+
37+ it "does not create a serializable resource" do
38+ @test_case . assert_no_file "app/serializable/serializable_dummy.rb" do
39+ @test_case . run_generator ( [ model_name ] )
40+ end
41+ end
42+ end
43+ end
You can’t perform that action at this time.
0 commit comments