如何通过预期参数来干扰调用方法的断言?

时间:2014-05-23 17:43:27

标签: ruby rspec

我需要编写测试传递给方法的参数的示例。

选项#1将接收的参数作为主题返回,以便验证部分可以非常简洁:

subject do
  color = nil
  pen_double.should_receive(:color=) do |arg|
    color = arg
  end
  color
end

context ...
  it { should == 'red' }
end

context ...
  it { should == 'green' }
end

此选项的问题在于“主题”部分笨重。当我开始测试其他方法(有许多方法需要测试)时,它就成了大问题。

选项#2不使用“主题”。相反,它写道:

context ...
  it { pen_double.should_receive(:color=).with('red') }
end

context ...
  it { pen_double.should_receive(:color=).with('green') }
end

显然现在'它'部分不够干净。

我忽略了第三种选择吗?

1 个答案:

答案 0 :(得分:0)

这不是一个不同的选项,但您可以通过提取辅助方法来改进选项2:

context ...
  it { should_be_set_to 'red' }
end

context ...
  it { should_be_set_to 'green' }
end

def should_be_set_to(color)
  pen_double.should_receive(:color=).with color
end

这是DRY,比使用主题块更简洁,并且可以在不阅读辅助方法的情况下理解。 (你可能想出一个比我更好的方法名,因为你知道域。)

相关问题