我正在学习rspec,我很好奇我可以针对以下编码问题运行的一些测试示例,其中我需要创建一个带有长字符串的对象并返回其中每个单词的频率,类似于下面的代码:
WordTracker.new('Toy boat toy boat toy boat').frequency
{
"toy" => 3,
"boat" => 3
}
答案 0 :(得分:0)
似乎像数据驱动的方法最适合这样的事情。怎么样?
describe WordTracker do
describe '#frequency' do
[
{
in: '',
out: {}
},
{
in: 'toy boat toy boat toy boat',
out: { 'toy' => 3, 'boat' => 3 }
},
{
in: 'toy',
out: { 'toy' => 1 }
}
].each do |example|
it "should convert #{example[:in]} to #{example[:out]}" do
expect(WordTracker.new(example[:in]).frequency).to eql(example[:out])
end
end
end
end
把它扔到一起,可能不会干净利落,但是嘿,你正在学习,好运动。
答案 1 :(得分:0)
describe WordTracker do
context '#frequency' do
{'toy boat toy boat toy boat'=>{'toy'=>3, 'boat'=>3},
'toy boat boat toy boat fred'=>{'toy'=>2, 'boat'=>3, 'fred'=>1},
'etc'=>{'etc'=>1}
}.each do |given, expected|
specify "for '#{given}' expect '#{expected}'" do
expect(WordTracker.new(given).frequency).to eq(expected)
end
end
end
end