我在具有GraphQL类型的Rails引擎内工作。
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
是我在mattr_accessor
中定义的方法,并且正在通过初始化程序从主Rails应用程序中获取特定的User类。
当我为此类型运行Rspec测试时,出现错误NameError: uninitialized constant Graph
所以我当时想像这样模拟整行field :user, RailsEngine.graph_user_type.constantize, 'The description of user'
:
before do
user_type = double('Graph::User::Types::User')
allow(described_class.fields['user']).to receive(:constantize).and_return(user_type)
end
我也尝试过allow(described_class.fields['user']).to receive(:type).and_return(user_type)
也无济于事!
但是我仍然遇到相同的错误!有什么想法吗?
Failure/Error: field :user, RailsEngine.graph_user_type.constantize, 'The description of user'
NameError:
uninitialized constant Graph```
before do
user_type = double('Graph::User::Types::User')
allow(described_class.fields['user']).to receive(:constantize).and_return(user_type)
end
您需要了解allow
方法的作用。它带一个对象,稍后用.to receive(...)
设置期望值。
似乎更有意义的是:
allow(RailsEngine).to receive(:graph_user_type).and_return('Graph::User::Types::User')
或者,如果您需要它来返回双精度数,则可以像
allow(RailsEngine).to receive_message_chain('graph_user_type.constantize').and_return(user_type)
https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains
通过这种方式,您可以控制返回的RailsEngine.graph_user_type
,并将其作为第二个参数传递给field
。
所以问题隐藏在这里
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.
由于我从主应用程序通过初始化程序将方法graph_user_type
从主应用程序获取到引擎,因此在加载规范之前,已经抛出了错误-因此在规范内对其进行模拟是没有用的。
解决方案是将主应用程序初始化程序必须具有的相同功能添加到引擎内部的虚拟初始化程序中(指示数据已被模拟)
这是我的初始化程序:RailsEngine.graph_user_type = 'Graph::User::Types::User'
这是我在Engine中的虚拟初始化程序:RailsEngine.graph_user_type = 'MockUserType'