我想在名为Debug的mixin(模块)的实例方法上运行基本的RSpec单元测试。以下是Debug mixin的文件内容:
module Debug
public
def class_info?
"#{self.class.name}"
end
end
当我运行irb
并将Debug mixin包含在命令require_relative './mixins/debug.rb'
和include Debug
中,然后调用Debug.class_info?
时,它会成功返回"Module"
然后,如果我使用以下RSpec单元测试运行rspec
以确认RSpec上下文可以访问mixin的实例方法,则测试成功通过:
require_relative '../../mixins/debug.rb'
RSpec.describe Debug, "#class_info?" do
include Debug
before(:each) do
@class_info_instance_method = Debug.instance_methods[0].to_s
end
context "with mixins" do
it "has class info instance method" do
expect(@class_info_instance_method).to eq "class_info?"
end
end
end
最后,我将RSpec单元测试更改为如下,因此它实际上调用了Debug mixin的class_info?
实例方法:
require_relative '../../mixins/debug.rb'
RSpec.describe Debug, "#class_info?" do
include Debug
before(:each) do
@class_info = Debug.class_info?
end
context "with mixins" do
it "shows class info" do
expect(@class_info).to eq "Module"
end
end
end
但是现在当我从命令行运行rspec
时,为什么会返回以下错误? (注意:即使在之前的RSpec单元测试设置中#1这完全相似,我检查过我可以成功访问这个Debug mixin实例方法)
1) Debug#class_info? with mixins shows class info
Failure/Error: @class_info = Debug.class_info?
NoMethodError:
undefined method `class_info?' for Debug:Module
注意:我已在RubyTest GitHub repo中分享了上述代码。
ruby -v
)rspec -v
)答案 0 :(得分:1)
当您包含模块时,这些方法将成为包含的类中的实例方法。 Debug.class_info?
不起作用,因为没有类方法class_info?
。我也不确定你在测试中包含模块的方式是最好的方法。这样的事情会起作用吗?
require_relative '../../mixins/debug.rb'
class TestClass
include Debug
end
RSpec.describe Debug, "#class_info?" do
let(:test_instance) { TestClass.new }
context "with mixins" do
it "shows class info" do
expect(test_instance.class_info?).to eq "TestClass"
end
end
end