ruby-on-rails - 将更清晰的描述传递给 RSpec `its` 方法

标签 ruby-on-rails testing rspec

我是 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

然后我了解了 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

由于 its 不接受 2 个参数而失败,但是删除消息工作正常。问题是,如果测试失败,失败示例部分下的消息只是说

rspec ./spec/models/account_spec.rb:23 # Account when new account_attributes

这并不过分帮助。

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

最佳答案

您可以定义一个 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

关于ruby-on-rails - 将更清晰的描述传递给 RSpec `its` 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12426907/

相关文章:

angularjs - 如果元素包含值,如何在 Protractor 中退出测试用例

ruby-on-rails - Rspec 的 DRY 问题我该如何解决

ruby-on-rails - 使用 RSpec 在 Rails 引擎中测试代码

javascript - 如何使用 jQuery 从多个下拉框中获取总计?

ruby-on-rails - 执行失败: Error: "\xFE" from ASCII-8BIT to UTF-8

ruby-on-rails - 从我的应用程序代码中获取数据并进入我的 rspec 测试

ruby-on-rails - PGError : ERROR: source database "template1" is being accessed by other users

java - Flesch-Kincaid 测试 (java)

typescript - 如何使用 Joi 验证自定义类型?

ruby-on-rails - rspec 没有说预期的 : 15. 35,使用 == 得到 : 15. 35,这对我来说没有意义?