File tree Expand file tree Collapse file tree 2 files changed +79
-0
lines changed
Expand file tree Collapse file tree 2 files changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ # frozen_string_literal: true
2+
3+ module Alchemy
4+ class PageServiceType < ActiveModel ::Type ::Value
5+ def cast ( value )
6+ return nil if value . nil?
7+
8+ value . constantize
9+ end
10+
11+ def assert_valid_value ( value )
12+ return if value . nil?
13+
14+ begin
15+ klass = value . constantize
16+ rescue NameError
17+ raise ArgumentError , "Service class \" #{ value } \" could not be found. Make sure it is defined and available."
18+ end
19+
20+ unless klass < BasePageService
21+ raise ArgumentError , "Service class \" #{ value } \" must be a subclass of Alchemy::BasePageService."
22+ end
23+ end
24+ end
25+ end
Original file line number Diff line number Diff line change 1+ # frozen_string_literal: true
2+
3+ require "rails_helper"
4+
5+ module Alchemy
6+ RSpec . describe PageServiceType do
7+ subject ( :type ) { described_class . new }
8+
9+ # A class without a #call method
10+ let ( :non_service_class ) do
11+ Class . new
12+ end
13+
14+ before do
15+ stub_const ( "NotAService" , non_service_class )
16+ end
17+
18+ describe "#cast" do
19+ context "with nil" do
20+ it "returns nil" do
21+ expect ( type . cast ( nil ) ) . to be_nil
22+ end
23+ end
24+
25+ context "with a valid class name" do
26+ it "returns the class constant" do
27+ expect ( type . cast ( "DummyPageService" ) ) . to eq ( DummyPageService )
28+ end
29+ end
30+ end
31+
32+ describe "#assert_valid_value" do
33+ it "accepts nil" do
34+ expect { type . assert_valid_value ( nil ) } . not_to raise_error
35+ end
36+
37+ it "accepts a valid service class name" do
38+ expect { type . assert_valid_value ( "DummyPageService" ) } . not_to raise_error
39+ end
40+
41+ it "raises for a non-existent class" do
42+ expect { type . assert_valid_value ( "DoesNotExist" ) } . to raise_error (
43+ ArgumentError , /could not be found/
44+ )
45+ end
46+
47+ it "raises for a class that is not a subclass of BasePageService" do
48+ expect { type . assert_valid_value ( "NotAService" ) } . to raise_error (
49+ ArgumentError , /must be a subclass of Alchemy::BasePageService/
50+ )
51+ end
52+ end
53+ end
54+ end
You can’t perform that action at this time.
0 commit comments