如何在rspec中合并匹配器?

时间:2013-04-09 07:51:13

标签: ruby rspec2

这是我的规格:

   it "should convert doc successfully" do
      @response = SharpOffice::Office.process(File.expand_path("spec/fixture/test.doc"))
      @response[:status].should == 'ok'
      File.exist?(@response[:pdf_path]).should be_true
      File.exist?(@response[:swf_path]).should be_true
      File.exist?(@response[:cover_path]).should be_true
    end

    it "should convert ppt successfully" do
      @response = SharpOffice::Office.process(File.expand_path("spec/fixture/test.ppt"))
      @response[:status].should == 'ok'
      File.exist?(@response[:pdf_path]).should be_true
      File.exist?(@response[:swf_path]).should be_true
      File.exist?(@response[:cover_path]).should be_true
    end

    it "should convert xls successfully" do
      @response = SharpOffice::Office.process(File.expand_path("spec/fixture/test.xls"))
      @response[:status].should == 'ok'
      File.exist?(@response[:pdf_path]).should be_true
      File.exist?(@response[:swf_path]).should be_true
      File.exist?(@response[:cover_path]).should be_true
    end

如何合并重复?感谢

2 个答案:

答案 0 :(得分:1)

您可以在新的conversion_helpers.rb文件中声明自定义匹配器:

RSpec::Matchers.define :be_converted_successfully do
  match do |conversion_response|
    conversion_response[:status] == 'ok' && File.exist?(conversion_response[:pdf_path]) && File.exist?(conversion_response[:swf_path]) && File.exist?(conversion_response[:cover_path])
  end
end

然后在您的规范require 'conversion_helpers'中,您可以执行以下操作:

it "should convert doc successfully" do
  SharpOffice::Office.process(File.expand_path("spec/fixture/test.doc")).should be_converted_successfully
end

it "should convert ppt successfully" do
  SharpOffice::Office.process(File.expand_path("spec/fixture/test.ppt")).should be_converted_successfully
end

it "should convert xls successfully" do
  SharpOffice::Office.process(File.expand_path("spec/fixture/test.xls")).should be_converted_successfully
end

虽然在实际测试中,尝试追踪错误可能会非常烦人。但这是一个不同的问题。

答案 1 :(得分:0)

使其成为一种功能?
将函数描述放在describe块

def convert_expectation(resp)
  resp[:status].should == 'ok'
  File.exist?(resp[:pdf_path]).should be_true
  File.exist?(resp[:swf_path]).should be_true
  File.exist?(resp[:cover_path]).should be_true
end  

it "should bla blabla" do
  resp = SharpOffice::Office.process(File.expand_path("spec/fixture/test.xls"))
  convert_expectation(resp)
end