我有一帮非常重复RSpec的测试,都具有相同的格式:如何在Rspec中进行一次没有Shoulda的线路测试?
it "inserts the correct ATTRIBUTE_NAME" do
@o.ATTRIBUTE_NAME.should eql(VALUE)
end
这将是很好,如果我可以只让一条线测试,如:
compare_value(ATTRIBUTE_NAME, VALUE)
但早该没有按”似乎是面向这些类型的测试。还有其他的选择吗?
我有一帮非常重复RSpec的测试,都具有相同的格式:如何在Rspec中进行一次没有Shoulda的线路测试?
it "inserts the correct ATTRIBUTE_NAME" do
@o.ATTRIBUTE_NAME.should eql(VALUE)
end
这将是很好,如果我可以只让一条线测试,如:
compare_value(ATTRIBUTE_NAME, VALUE)
但早该没有按”似乎是面向这些类型的测试。还有其他的选择吗?
如果你想让它更清楚地阅读和只有1号线我会写一个自定义的RSpec的帮手。假设我们有下面的类,我们要测试:
class MyObject
attr_accessor :first, :last, :phone
def initialize first = nil, last = nil, phone = nil
self.first = first
self.last = last
self.phone = phone
end
end
我们可以编写以下匹配:
RSpec::Matchers.define :have_value do |attribute, expected|
match do |obj|
obj.send(attribute) == expected
end
description do
"have value #{expected} for attribute #{attribute}"
end
end
然后写我们可以做类似的测试:
describe MyObject do
h = {:first => 'wes', :last => 'bailey', :phone => '111.111.1111'}
subject { MyObject.new h[:first], h[:last], h[:phone] }
h.each do |k,v|
it { should have_value k, v}
end
end
如果你把所有这些放在一个文件中调用matcher.rb并运行,输出如下:
> rspec -cfn matcher.rb
MyObject
should have value wes for attribute first
should have value bailey for attribute last
should have value 111.111.1111 for attribute phone
Finished in 0.00143 seconds
3 examples, 0 failures
你摇滚。谢谢。 – 2011-04-14 15:51:16
@Jeremy Smith不客气! – Wes 2011-04-14 17:44:33
subject { @o }
it { attribute.should == value }
我不得不使用subject.attribute.should ==值。这是必要的还是我做错了什么? – 2011-04-14 01:13:57
我发现这个伟大的工程:
specify { @o.attribute.should eql(val) }
有时我很遗憾将subject
作为最终用户设备。据介绍,以支持扩展(如shoulda
的匹配),所以你可以这样写的例子:
it { should do_something }
像这样的例子,但是,不读得好:
it { subject.attribute.should do_something }
如果你要使用subject
明确,然后在本例中明确地引用它,我建议使用specify
代替it
:
specify { subject.attribute.should do_something }
底层的语义是相同的,但是这个^^可以被朗读。
难道你不能把它们放在单个'it'块中,并且对每个属性使用'.should =='? – Dogbert 2011-04-13 23:51:34