【问题标题】:Simplifying rspec unit tests简化 rspec 单元测试
【发布时间】:2014-09-19 01:04:43
【问题描述】:

在 rspec 的单元测试中,很多时候必须同时指定 context 和 let 有点麻烦而且似乎没有必要。例如:

context 'type = :invalid' do
  let(:type) { :invalid }

  it { expect { subject }.to raise_error(ArgumentError) }
end

如果我能做这样的事情会更好(通过大量测试):

let_context type: :invalid do
  it { expect { subject }.to raise_error(ArgumentError) }
end

该方法将为我定义一个上下文和 let(s),上下文的参数将类似于 type = :invalid 或 let(:type) { :invalid },因为除了这个变量已更改的事实之外,我没有其他要说的了.

【问题讨论】:

    标签: ruby unit-testing rspec


    【解决方案1】:

    实际上,您可以通过遵循一些http://betterspecs.org 的建议来减少行数:

    context 'type = :invalid' do
      let(:type) { :invalid }
      it { expect{ subject }.to raise_error(ArgumentError)
    end
    

    您的变体可以读作

    它会引发错误,但会引发错误

    虽然这更干净

    它预计会受到 raise_error 的影响

    不过还是离题了:)

    UPD

    哦。真的你不能将两个块传递给方法,所以下面的例子不是有效的 Ruby :)

    context(:type) { :invalid } do
      it{ expect{ subject }.to raise_error(ArgumentError)
    end
    

    虽然你的例子

    let_context type: :invalid do
      ...
    end
    

    不会像 let 那样做延迟执行

    【讨论】:

    • 是的,这很好。我实际上将我的一些规范转换为使用这种语法。那肯定更好,但不能回答主要问题;)
    • 基于此编辑问题。虽然我很挑剔:你为什么不能使用expects。说it { expects { etc.. 会很好。我认为您可以在 rspec 配置中为方法设置别名,所以我可能会考虑这个 ;)
    • @BrianUnderwood let 与context 分开居住的主要原因是隔离。在您的情况下let_context type: :invalid do 您缺少隔离。其次是懒惰。这是测试非常重要的要求。你不想得到难以调试的副作用:)
    • 没错,let_context type: -> { :invalid } 怎么样。不过,开始变得不那么方便了
    • 使用 procs/lambdas 是非常尴尬的解决方案 :)
    【解决方案2】:

    在 rspec 的单元测试中很多时候必须同时指定 context 和 let 有点麻烦

    听起来您可能想使用RSpec shared context。

    更新

    RSpec 为您建议的语法提供了一个 DSL:a shared example。例如:

    RSpec.shared_examples "some thang" do |type|
     it { expect { subject }.to raise_error(ArgumentError) }
    end
    
    RSpec.shared_examples "a thang" do
      include_examples "some thang", :invalid
      # Or whatever is more appropriate for your domain
      # I.e., If you're testing subclass behavior use it_should_behave_like()
    end
    

    【讨论】:

    • 是的,我已经查看(并且偶尔使用)shared_context,它可能会有所帮助,但在这种情况下,我说的是每个 context 块都有一个 it(其中每个context 块只定义了一个 let)。真正好的和英语的东西就像 when(type: :invalid) { expect { subject }.to raise_error }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    相关资源
    最近更新 更多