RSpec Matchers用于函数参数

时间:2014-02-24 20:10:44

标签: ruby rspec

我是编写自定义匹配器的新手,大多数示例都涵盖了非常小的设置。编写从具有参数的模块扩展函数的匹配器的正确方法是什么。我是否需要为实际块提供函数参数input?感谢。

# My Example:
RSpec::Matchers.define :total do |expected|
  match do |input, actual|
    actual.extend(Statistics).sample(input) == expected
  end
end

# Before:
describe Statistics do
  it 'should not be empty' do
    expect(Statistics.sample(input)).not_to be_empty
  end
end

1 个答案:

答案 0 :(得分:2)

这取决于你想要测试的内容。如果您只是想测试模块是否包含方法,可能是这样的:

module Statistics
  def sample
  end
end

class Test
end

RSpec::Matchers.define :extend_with do |method_name|
  match do |klass|
    klass.extend(Statistics).respond_to?(method_name)
  end
end

describe Statistics do
  subject { Test.new }
  it { should extend_with(:sample) }
end

如果要测试返回的值,可以将其作为参数添加,或链接匹配器:

module Statistics
 def sample(input)
    41 + input
  end
end

class Test
end

RSpec::Matchers.define :extend_with do |method_name, input|
  match do |klass|
    @klass = klass
    @klass.extend(Statistics).respond_to?(method_name)
  end
  chain :returning_value do |value|
    @klass.extend(Statistics).__send__(method_name, input) == value
  end
end

describe Statistics do
  subject { Test.new }
  it { should extend_with(:sample) }
  it { should extend_with(:sample, 2).returning_value(43) }
end

匹配器DSL非常灵活。您不必像在docs中那样将您的参数命名为“实际”和“预期” - 编写规范以便他们讲述您的代码。