向 RSpec `its` 方法传递更清晰的描述

Top*_*gio 5 testing rspec ruby-on-rails

我是 RSpec 新手,但我真的很喜欢编写测试的简单性,并且在学习 RSpec 的新功能时,我不断地重构它们以使其更加清晰。所以,最初,我有以下内容:

describe Account do
  context "when new" do
    let(:account) { Account.new }
    subject { account }

    it "should have account attributes" do
      subject.account_attributes.should_not be_nil
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

后来我了解了该its方法,所以我尝试将其重写为:

describe Account do
  context "when new" do
    let(:account) { Account.new }
    subject { account }

    its(:account_attributes, "should not be nil") do
      should_not be_nil
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

由于its不接受 2 个参数,此操作失败,但删除消息效果很好。问题是,如果测试失败,失败示例部分下的消息只会显示

rspec ./spec/models/account_spec.rb:23 # Account when new account_attributes
Run Code Online (Sandbox Code Playgroud)

这并没有太大帮助。

那么,有没有一种方法可以将消息传递给its,或者更好的是,让它自动输出一条正常的消息?

zet*_*tic 4

您可以定义一个 RSpec 自定义匹配器:

RSpec::Matchers.define :have_account_attributes do
  match do |actual|
    actual.account_attributes.should_not be_nil
  end
  failure_message_for_should do
    "expected account_attributes to be present, got nil"
  end
end

describe Account do
  it { should have_account_attributes }
end
Run Code Online (Sandbox Code Playgroud)