【问题标题】:How to write expect {}.to raise_error when rspec's syntax is configured with only should当 rspec 的语法配置为 only should 时如何编写 expect {}.to raise_error
【发布时间】:2013-04-10 08:31:37
【问题描述】:

我在 rspec 上有这个配置:

config.expect_with :rspec do |c|
  c.syntax = :should
end

它使expect {}.to raise_error 无效,我怎么能用 should 语法编写这个引发错误的测试?

【问题讨论】:

  • 设置c.syntax = [:should, :expect]不是一个选项?

标签: ruby testing syntax rspec


【解决方案1】:

我建议仅当您无法使用最新的 RSpec expect { code() }.to raise_error 语法时才使用它:

lambda { foo( :bad_param ) }.should raise_error

lambda { foo( :bad_param ) }.should raise_error( ArgumentError )

foo( :bad_param ) 替换为您希望断言失败的任何 Ruby 代码,并将 ArgumentError 替换为您希望失败引发的任何异常类。

【讨论】:

  • 什么是Foo?你能说出你的代码基本上在做什么吗?
  • foo 是任何事物的通用编程术语,在这种情况下是方法。因此,将您想要测试的任何内容包装在 lambda 中 - 您可以将其重写为 lambda { my_method_to_test() }.should raise_error...
  • 非常奇怪的行为,因为这种做事方式应该被弃用 - 请参阅RSpec's New Expectation Syntax,“块与值语法的统一”段落。
  • @Gregory Goltsov:是的,它已被弃用,但 OP 专门要求使用旧语法,因为 expect 语法由于某种原因在他的项目中被阻止。我会在答案中澄清这一点。
【解决方案2】:

在可以使用expect 语法的测试中,我更喜欢在自己的describe 块中定义该测试,将测试内容(即expect { <this_content> })放入stabby lambda,将其粘贴到新的subject,并在 it 块中引用它,如下所示:

describe "some test that raises error" do
  let(:bad_statement) { something_that_raises_an_error }
  subject { -> { bad_statement } }
  it { should raise_error }
end

如果您愿意,您也可以完全取消 let 语句,并将其内容直接放在 subject 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多