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
6
6
# TODO(beauby): Implement versioning.
7
7
8
8
def copy_serializable_file
9
+ fail "#{ class_name } model not found." unless model_exists?
10
+
9
11
template 'serializable.rb.erb' ,
10
12
File . join ( 'app/serializable' , class_path ,
11
13
"#{ serializable_file_name } .rb" )
12
14
end
13
15
14
16
private
15
17
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
+
16
24
def serializable_file_name
17
25
"serializable_#{ file_name } "
18
26
end
@@ -22,7 +30,6 @@ def serializable_class_name
22
30
end
23
31
24
32
def model_klass
25
- # TODO(beauby): Ensure the model class exists.
26
33
class_name . safe_constantize
27
34
end
28
35
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