Pet*_*noy 11 testing rspec ruby-on-rails
我正在为我的应用添加更多的rspec测试,并希望测试一个ScoringMethods模块,它位于/lib/scoring_methods.rb中.所以我添加了一个/ spec/lib目录并在那里添加了scoring_methods_spec.rb.我需要spec_helper并设置describe块,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
现在methods[0]
是一个String,并且公共方法名称与正则表达式匹配没有问题.而"spec_helper"的相对路径是正确的.
问题是整个设置似乎没有使用rspec库.运行示例产生:
./spec/lib/scoring_methods_spec.rb:7: undefined method `match' for Spec::Rails::Example::RailsExampleGroup::Subclass_1::Subclass_1:Class (NoMethodError)
...
Run Code Online (Sandbox Code Playgroud)
似乎缺少整个期望和匹配支持.为了测试我的假设,我通过将"is_instance_of"替换为"is_foobar_of"来更改了工作助手规范.该测试完全失败,并说"is_foobar_of"不是目标对象的方法; 它,整个Spec :: Rails :: Example ...层次结构不存在.
我也尝试过使用其他匹配器.我试过"be_instance_of"和其他一些人.好像我没有正确地包含rspec库.
最后,ScoringMethods是一个模块,就像Helpers是模块一样.所以我认为可以测试一个模块(而不是像控制器和模型这样的类).
我非常感谢你对我做错了什么的想法.也许有更有效的方法来测试库模块?谢谢!
小智 11
您应该将测试块包含在"it"块中.例如:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe ScoringMethods do
describe "should have scorePublicContest method" do
it "should have a scorePublicContest method" do
methods = ScoringMethods.instance_methods
methods[0].should match(/scorePublicContest/)
end
end
end
Run Code Online (Sandbox Code Playgroud)
您会发现返回的方法名称不保证按文件中存在的顺序排列.
我们在测试模块时经常使用的模型是将模块包含在为测试创建的类中(在spec文件内)或包含在spec本身内.
归档时间: |
|
查看次数: |
6612 次 |
最近记录: |