[英]How do I make one line tests in Rspec without Shoulda?
I have a bunch of very repetitive rspec tests that all have the same format: 我有一堆非常重复的rspec测试,它们都具有相同的格式:
it "inserts the correct ATTRIBUTE_NAME" do
@o.ATTRIBUTE_NAME.should eql(VALUE)
end
It would be nice if I could just make one line tests like: 如果我能做一个像以下那样的线测试会很好:
compare_value(ATTRIBUTE_NAME, VALUE)
But shoulda doesn't seem to be geared toward these types of tests. 但是,似乎并不适合这些类型的测试。 Are there other alternatives?
还有其他选择吗?
Sometimes I regret exposing subject
as an end-user device. 有时我后悔将
subject
暴露为最终用户设备。 It was introduced to support extensions (like shoulda
matchers), so you can write examples like: 它被引入以支持扩展(如
shoulda
matchers),因此您可以编写如下示例:
it { should do_something }
Examples like this, however, do not read well: 但是,这样的例子读得不好:
it { subject.attribute.should do_something }
If you're going to use subject
explicitly, and then reference it explicitly in the example, I recommend using specify
instead of it
: 如果您要明确地使用
subject
,然后在示例中显式引用它,我建议使用specify
而不是it
:
specify { subject.attribute.should do_something }
The underlying semantics are the same, but this ^^ can be read aloud. 底层语义是相同的,但这个^^可以大声朗读。
I would write a custom RSpec helper if you want it to read more clearly and be only 1 line. 如果你想让它读得更清楚并且只有1行,我会写一个自定义的RSpec助手。 Suppose we have the following class we want to test:
假设我们要测试以下类:
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
We could write the following matcher: 我们可以编写以下匹配器:
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
Then to write the tests we could do something like: 然后编写测试我们可以做类似的事情:
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
If you put all of this in a file call matcher.rb and run it the following is output: 如果将所有这些放在文件中调用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
我发现这个很有效:
specify { @o.attribute.should eql(val) }
subject { @o }
it { attribute.should == value }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.