Rspec的未定义方法'+'。这是什么意思?

时间:2014-04-06 01:56:38

标签: ruby-on-rails ruby rspec

我正在撞墙,因为我对这个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)>'

就我而言,这不应该失败,我不知道为什么会失败。我的schema.rb将字段设为null false,我的模型使用numericity: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

我不知道问题是什么。一些帮助?

1 个答案:

答案 0 :(得分:4)

这是语法错误。您错过了.to之前和"can't be blank"之前的括号:

这一行应该是这样的:

期望(art_piece.errors [:cost] 。包含“不能为空”)

无论如何,我建议使用match_array替换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

PS:每个测试只实现一个期望是好的惯例。

最终的例子应该是这样的:

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

希望它会有所帮助:)