【问题标题】:How do I make one line tests in Rspec without Shoulda?如何在没有 Shoulda 的情况下在 Rspec 中进行单行测试?
【发布时间】:2011-04-13 23:42:58
【问题描述】:

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

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

如果我能做一行测试就好了:

compare_value(ATTRIBUTE_NAME, VALUE)

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

【问题讨论】:

  • 你不能把它们放在一个单独的it 块中,并为每个属性使用.should == 吗?

标签: ruby-on-rails ruby rspec shoulda


【解决方案1】:

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

it { should do_something }

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

it { subject.attribute.should do_something }

如果您要显式使用subject,然后在示例中显式引用它,我建议使用specify 而不是it

specify { subject.attribute.should do_something }

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

【讨论】:

    【解决方案2】:

    如果您希望它更清晰地阅读并且只有 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
    

    【讨论】:

      【解决方案3】:

      我发现这个效果很好:

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

      【讨论】:

        【解决方案4】:
        subject { @o }
        it { attribute.should == value }
        

        【讨论】:

        • 我不得不使用 subject.attribute.should == value。这是必要的还是我做错了什么?
        猜你喜欢
        • 1970-01-01
        • 2019-07-27
        • 2016-06-30
        • 2022-11-17
        • 2020-01-01
        • 1970-01-01
        • 2023-01-09
        • 2014-01-21
        • 2014-07-29
        相关资源
        最近更新 更多