我正在向我的应用程序添加更多 rspec 测试,并希望测试 ScoringMethods 模块,该模块位于 /lib/scoring_methods.rb 中。所以我添加了一个 /spec/lib 目录并在那里添加了scoring_methods_spec.rb。我需要 spec_helper 并这样设置描述块:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe ScoringMethods do
describe "should have scorePublicContest method" do
methods = ScoringMethods.instance_methods
methods[0].should match(/scorePublicContest/)
end
end
现在methods[0]
是一个字符串,将公共方法名称与正则表达式匹配没有问题。并且“spec_helper”的相对路径是正确的。
问题是整个设置似乎没有使用 rspec 库。运行示例产生:
./spec/lib/scoring_methods_spec.rb:7: undefined method `match' for Spec::Rails::Example::RailsExampleGroup::Subclass_1::Subclass_1:Class (NoMethodError)
...
似乎缺少整个 Expectation 和 Matcher 支持。为了测试我的假设,我通过将“is_instance_of”替换为“is_foobar_of”来更改工作帮助规范。该测试完全失败并说“is_foobar_of”不是目标对象的方法;它,整个 Spec::Rails::Example... 层次结构不存在。
我也尝试过使用其他匹配器。我试过“be_instance_of”和其他一些。看来我没有正确包含 rspec 库。
最后,ScoringMethods 是一个模块,就像 Helpers 是模块一样。所以我认为可以测试一个模块(而不是类,例如控制器和模型)。
我非常感谢您对我做错了什么的想法。也许有一种更有效的方法来测试库模块?谢谢!