我写了一个简单的类方法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
答案 0 :(得分: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
我正在假设你在这里所做的事情,但希望这个想法很明确。当测试失败时,这也将导致更有用的错误输出。希望这有帮助!
答案 1 :(得分:11)
显然有一种described_class
方法。
https://www.relishapp.com/rspec/rspec-core/docs/metadata/described-class
我认为它比subject.class
更干净,因为它不会引入另一个.
方法调用,这会降低可读性。
使用described_class
或subject.class
可能比在每个示例中明确提及类更干。但就我个人而言,我认为没有明确提及类名的语法突出显示有点令人失望,我认为它降低了可读性,尽管它在可维护性部门完全获胜。
关于最佳实践的问题出现了:
您是否应尽可能在.expect()
方法内外使用describe_class,或仅在expect()
方法内使用?
答案 2 :(得分:6)
这可能是一个老问题,但您始终可以使用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
答案 3 :(得分:4)
答案 4 :(得分:0)
使用subject
/ it
的替代方法是使用before
/ specify
:
describe '#destroy' do
context 'with children' do
before { @parent = FactoryGirl.create(:parent, children: FactoryGirl.create_list(:child, 2) }
specify { @parent.destroy.should be_false }
end
end
这将以RSpec的-fd
输出格式生成合理的描述:
#destroy
with children
should be false