我撞到墙了,因为我非常困惑这个rspec错误消息意味着什么。我正在测试一件艺术品是否有成本。以下是我的rspec片段:

let(:valid_art_piece){ { date_of_creation: DateTime.parse('2012-3-13'),
placement_date_of_sale: DateTime.parse('2014-8-13'), cost: 250, medium: 'sculpture',
availability: true } }

it 'requires a cost' do
  art_piece = ArtPiece.new(valid_art_piece.merge(cost: ''))
  expect(art_piece).to_not be_valid
  expect(art_piece.errors[:cost].to include "can't be blank")
end

错误消息:
1) ArtPiece requires a cost
 Failure/Error: expect(art_piece.errors[:cost].to include "can't be blank")
 NoMethodError:
   undefined method `+' for #<RSpec::Matchers::BuiltIn::Include:0x000001050f4cd0>
 # ./spec/models/artist_piece_spec.rb:30:in `block (2 levels) in <top (required)>'

就我而言,这不应该失败,我不知道为什么会失败。my schema.rb将该字段设置为null false,我的模型使用numericality:true选项对其进行验证。
class ArtPiece < ActiveRecord::Base
  validates_presence_of :date_of_creation
  validates_presence_of :placement_date_of_sale
  validates :cost, numericality: true
  validates_presence_of :medium
  validates_presence_of :availability
end

我不知道有什么问题。有什么帮助?

最佳答案

这是一个语法错误。您错过了.to之前和"can't be blank"之前的括号:
这行应该是这样的:
期望(艺术品错误[成本])包括(“不能为空”)
无论如何,我建议使用match_数组替换include方法

it 'requires a cost' do
  art_piece = ArtPiece.new(valid_art_piece.merge(cost: ''))
  expect(art_piece).to_not be_valid
  expect(art_piece.errors[:cost]).to match_array (["can't be blank"])
end

注:一次测试只实现一个期望值是一个很好的约定。
最后一个例子应该是这样的:
context "art_piece" do
  subject { ArtPiece.new(valid_art_piece.merge(cost: '')) }

  it 'should_not be valid' do
     expect(subject).to_not be_valid
  end

  it 'requires a cost' do
    expect(subject.errors[:cost]).to match_array (["can't be blank"])
  end
end

希望能有所帮助:)

07-26 09:35
查看更多