如何在没有Shoulda的情况下在Rspec中进行一次线性测试?

时间:2011-04-13 23:42:58

标签: ruby-on-rails ruby rspec shoulda

我有一堆非常重复的rspec测试,它们都具有相同的格式:

it "inserts the correct ATTRIBUTE_NAME" do
     @o.ATTRIBUTE_NAME.should eql(VALUE)
end

如果我可以进行一次测试,那就太好了。

compare_value(ATTRIBUTE_NAME, VALUE)

但是,似乎并不适合这些类型的测试。还有其他选择吗?

4 个答案:

答案 0 :(得分:11)

有时候我很遗憾将subject作为最终用户设备公开。它是为支持扩展(如shoulda匹配器)而引入的,因此您可以编写如下示例:

it { should do_something }

然而,这样的例子读得不好:

it { subject.attribute.should do_something }

如果您要明确使用subject,然后在示例中明确引用它,我建议您使用specify代替it

specify { subject.attribute.should do_something }

底层语义相同,但这个^^可以大声朗读。

答案 1 :(得分:3)

如果你想要更清楚地阅读并且只有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

答案 2 :(得分:0)

我发现这很有效:

specify { @o.attribute.should eql(val) }

答案 3 :(得分:-1)

subject { @o }
it { attribute.should == value }