why
why

Reputation: 24851

How to merge matchers in rspec?

This is my specs:

   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

How to merge repetition ? thanks

Upvotes: 0

Views: 569

Answers (2)

stef
stef

Reputation: 14268

You could declare a custom matcher in a new conversion_helpers.rb file:

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

Then in your spec, require 'conversion_helpers' and you can do:

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

Although, in actual testing this could get quite annoying trying to track down a bug. But that's a different issue.

Upvotes: 1

mhd
mhd

Reputation: 4687

make it as a function?
put the function description in the describe block

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

Upvotes: 0

Related Questions