RSpec测试类在没有实际文件的模块内
我有一个用于在我的商店中创建零件产品的模块,名为ErpPartsService::Builder,通过该模块,我构建了一个助手类CategoryByaluberIDFetcher,我只在模块内部使用,而不是在其他任何地方使用。我把它放在app/services/erp\u parts\u service/builder.rb文件中 这是我的密码:RSpec测试类在没有实际文件的模块内,rspec,rspec-rails,Rspec,Rspec Rails,我有一个用于在我的商店中创建零件产品的模块,名为ErpPartsService::Builder,通过该模块,我构建了一个助手类CategoryByaluberIDFetcher,我只在模块内部使用,而不是在其他任何地方使用。我把它放在app/services/erp\u parts\u service/builder.rb文件中 这是我的密码: module ErpPartsService class CategoryByLauberIdFetcher < Service # Thi
module ErpPartsService
class CategoryByLauberIdFetcher < Service # This is the helper class that I want to test.
def initialize(...)
...
end
def call(lauber_id:)
...
end
end
class Builder < Service
def initialize(
category_by_lauber_id: CategoryByLauberIdFetcher
)
@category_by_lauber_id = category_by_lauber_id
end
def call(...)
...
end
private
def get_category_by_lauber_id(id)
@category_by_lauber_id.call(lauber_id: id)
end
end
end
当我运行它们时,我得到:
NameError:
uninitialized constant ErpPartsService::CategoryByLauberIdFetcher
我为构建器类编写了测试
规范/服务/erp\u零件\u服务/builder\u规范rb
它们工作得很好。我遗漏了什么?看起来像是自动装弹机问题: 看到常量ErpPartsService::Builder,自动加载程序需要一个文件erp\u parts\u service/Builder.rb,它找到了它。。。但是 看到ErpPartsService::CategoryByLaberIDFetcher autoloader试图通过_lauber_id_fetcher.rb查找erp_parts_service/category_,但失败,因为此类的定义在erp_parts_service/builder.rb中 添加require以显式加载包含要测试的类的文件
require 'erp_parts_service/builder.rb'
RSpec.describe ErpPartsService::CategoryByLauberIdFetcher do
it '...' do
...
end
end
或者最好将每个类放在一个单独的文件中,并遵守约定。不仅是自动加载器,其他加入项目的人也会在不存在的文件中查找此类
我知道您已经提到,您只想在模块内部使用这个类,但这不是使其私有化的方法。你只是让人讨厌使用它,而不是保护它不被使用 Thanx成功了。注意,我只在这个模块中使用这个类,我不认为我已经让使用…Thanx变得很烦人。同意不同意,你的问题证明了它现在的组织方式对人们和自动加载器来说是混乱的。事实是:你不只是在这个模块中使用它,你在规范中单独使用它。我不确定这是否是一种特殊的代码气味,但感觉就像一种。无论如何,这只是一个建议,我很高兴我能帮助解决最初的问题。干杯
RSpec.describe ErpPartsService::Builder do
it '...' do
...
end
end
require 'erp_parts_service/builder.rb'
RSpec.describe ErpPartsService::CategoryByLauberIdFetcher do
it '...' do
...
end
end