lul*_*ala 17 ruby testing rspec rspec2
我写了一个简单的类方法Buy.get_days(string),并试图用不同的文本字符串输入来测试它.不过我觉得它很啰嗦.
subject的方法,我可以只保留在通过不同的参数和检查结果?it?谢谢
describe Buy do
describe '.get_days' do
it 'should get days' do
Buy.get_days('Includes a 1-weeknight stay for up to 4 people')
.should == 1
end
it 'should get days' do
Buy.get_days('Includes a 1-night stay in a King Studio Room with stone fireplace')
.should == 1
end
it 'should get days' do
Buy.get_days('Includes 4 nights/5 days at the Finisterra Hotel for up to two adults and two children (staying in the same room)')
.should == 4
end
end
end
Run Code Online (Sandbox Code Playgroud)
Mat*_*ers 13
没有subject相应的方法来调用方法,所以使用it是这里的方法.我看到你的代码所呈现的问题是,它实际上并没有解释什么,你是为测试.我会写更多的东西:
describe Buy do
describe '.get_days' do
it 'should detect hyphenated weeknights' do
Buy.get_days('Includes a 1-weeknight stay for up to 4 people').should == 1
end
it 'should detect hyphenated nights' do
Buy.get_days('Includes a 1-night stay in a King Studio Room with stone fireplace').should == 1
end
it 'should detect first number' do
Buy.get_days('Includes 4 nights/5 days at the Finisterra Hotel for up to two adults and two children (staying in the same room)').should == 4
end
end
end
Run Code Online (Sandbox Code Playgroud)
我假设你在这里做了什么,但希望这个想法很明确.当测试失败时,这也将导致更有用的错误输出.希望这可以帮助!
ahn*_*cad 11
显然有一种described_class方法.
https://www.relishapp.com/rspec/rspec-core/docs/metadata/described-class
我认为它比它更清晰subject.class,因为它没有引入另一个.方法调用,这降低了可读性.
使用described_class或者subject.class可能比在每个示例中明确提及类更干.但就我个人而言,我认为没有明确提及类名的语法突出显示有点令人失望,我认为它会降低可读性,尽管它在可维护性部门完全胜出.
关于最佳实践的问题出现了:
您是否应尽可能在.expect()方法内外使用describe_class ,或仅在expect()方法内使用?
这可能是一个老问题,但你可以随时使用subject.class:
describe Buy do
describe '.get_days' do
it { expect(subject.class.get_days('Includes a 1-weeknight stay for up to 4 people')).to eq 1 }
end
end
Run Code Online (Sandbox Code Playgroud)