Search code examples
ruby-on-railsrspecgraphqlrails-engines

How to mock a GraphQL type in Rails engine rspec?


I'm working inside a Rails engine where I have a GraphQL type.

module RailsEngine
  module Graph
    module RailsEngine
      module Types
        MyClass = GraphQL::ObjectType.define do
          # some working code here

          field :user, RailsEngine.graph_user_type.constantize, 'The description of user'
        end
      end
    end
  end
end

graph_user_type is a method that I define in the mattr_accessor and am getting a specific class of User from the main Rails app through the initializer.

When I'm running my Rspec tests for this type, I'm getting an error NameError: uninitialized constant Graph

So I was thinking of mocking the whole line field :user, RailsEngine.graph_user_type.constantize, 'The description of user' like this:

  before do
    user_type = double('Graph::User::Types::User')
    allow(described_class.fields['user']).to receive(:constantize).and_return(user_type)
  end

I've also tried allow(described_class.fields['user']).to receive(:type).and_return(user_type) also to no avail!

But I'm still getting the same error! Any ideas?

Failure/Error: field :user, RailsEngine.graph_user_type.constantize, 'The description of user'

NameError:
  uninitialized constant Graph```



Solution

  • So the issue was hidden here

    graph_user_type is a method that I define in the mattr_accessor and am getting a specific class of User from the main Rails app through the initializer.

    Since I was getting the method graph_user_type through the initializer to the engine from the main app, before the spec was loaded, the error was already thrown - so it was useless to mock it inside the spec.

    The solution was to add the very same thing that the main app initializer had to the dummy initializer inside the engine (with an indication that the data is mocked)

    This was my initializer: RailsEngine.graph_user_type = 'Graph::User::Types::User'

    This was my dummy initializer inside Engine: RailsEngine.graph_user_type = 'MockUserType'