我有以下测试,使用RSpec
编写 spec/services/aquatic/factory_spec.rb
describe Hobby::Aquatic::Factory do
let(:factory) { Hobby::Aquatic::Factory.instance }
describe "singleton" do
it "should be the same object" do
Hobby::Aquatic::Factory.instance.should be factory
end
it "raise error if given junk" do
expect {factory.hobby("junk")}.to raise_error
end
end
end
spec/services/aquatic/hobbies_spec.rb
describe Hobby::Aquatic do
it "creates fishing" do
expect { Hobby::Aquatic::Fishing.new }.to_not raise_error
end
end
并定义了以下模块/类
app/services/aquatic/factory.rb
require 'singleton'
module Hobby
module Aquatic
class Factory
include Singleton
def self.instance
@@instance ||= new
end
def hobby(name)
return Fishing.new if name == "fishing"
return Surfing.new if name == "surfing"
raise ArgumentError, "Unknown hobby for supplied name"
end
end
end
end
app/services/aquatic/hobbies.rb
module Hobby
module Aquatic
class Fishing
end
class Surfing
end
end
end
当我运行测试时,Factory测试所有传递正常,但Hobby::Aquatic::Fishing
对象的测试导致:
Failure/Error: expect { Hobby::Aquatic::Fishing.new }.to_not raise_error
expected no Exception, got #<NameError: uninitialized constant Hobby::Aquatic::Fishing> …
我做错了什么?
答案 0 :(得分:1)
在require_relative 'hobbies'
下方添加require 'singleton'
以解决此问题。
我不确定为什么Rails
会自动加载factory
而不加载hobbies
,但这样做有效。