What's the proper way to force an RSpec test to fail?

我在考虑1.should == 2英镑,不过可能还有更好的.

推荐答案

fail/raise就可以了(它们是彼此的别名).

实例

specify "this test fails" do
  raise "this is my failure message"
end

失败于:

1) failing this test fails
   Failure/Error: raise "this is my failure message"

   RuntimeError:
     this is my failure message

Select

如果你想在一个规范中使用raise/fail,你应该考虑到可能有更明确的方式来写你的期望.

此外,raise/fail不能很好地与aggregate_failures配合使用,因为异常会使块短路,并且不会运行任何后续匹配器.

将测试标记为挂起

如果需要将测试标记为挂起以确保返回测试,可以使用fail/raise,但也可以使用pending.

# ? Instead of this:
it "should do something" do
   # ...
   raise "this needs to be implemented"
end

# ✅ Try this:
it "should do something" do
  pending "this needs to be implemented"
end

断言未调用块

如果需要确保块未被执行,请考虑使用yield matchers.例如:

describe "Enumerable#any?" do
  # ? Instead of this:
  it "doesn't yield to the block if the collection is empty" do
    [].any? { raise "it should not call this block" }
  end

  # ✅ Try this:
  it "doesn't yield to the block if the collection is empty" do
    expect { |b| [].any?(&b) }.not_to yield_control
  end
end

Ruby-on-rails相关问答推荐

使用turbo流的部分渲染在rails 7中不起作用.

Data-turbo-stream=&FALSE&QOOT;不适用于带有方法POST的表单

如何判断字符串中是否包含列值

如何使用继承类 (STI) 获取 Ruby on Rails 类中基类的实例

比较 Rails 中的日期

键入rails 控制台无法启动?

SQLite3::BusyException

如何在rails中发回js.haml

Rails:参数太少

Heroku 错误 R14(超出内存配额):我该如何解决?

Ruby如何写入Tempfile

Rails data-disable-with re-enable 按钮

不允许请求来源:使用 Rails5 和 ActionCable 时的 http://localhost:3001

Rails 3.1 插件 gem、虚拟测试应用程序、rspec

RubyMine - 关闭在空行中间单击的功能

ActiveRecord 查找现有表索引

Rails 控制台中手动更新属性值的验证问题

Post.all.map(&:id) 是什么意思?

从 ActiveRecord 对象中提取两个属性的快捷方式?

使用设计创建一个用户显示页面