Rspec验证范围的唯一性

时间:2013-05-07 19:03:00

标签: ruby-on-rails rspec rspec-rails

我在Line模型中有这个

validates :home_team, :uniqueness => { :scope => [:visiting_team, :event_datetime],
:message => "** DOUBLE EVENT **" }  

我的规格中有这个

describe Line do
  it { should validate_uniqueness_of(:home_team).scoped_to(:visiting_team, :event_datetime) }  

我收到此错误...

故障:

1) Line 
 Failure/Error: 

it { should validate_uniqueness_of(:home_team).scoped_to(:visiting_team, :event_datetime) }
   Did not expect errors to include "has already been taken" when home_team is set to "arbitrary_string", got error: 
# ./spec/models/line_spec.rb:7:in `block (2 levels) in <top (required)>'

为什么会失败的任何想法?

3 个答案:

答案 0 :(得分:38)

我认为你需要这样做才能通过

it { should validate_uniqueness_of(:home_team).scoped_to(:visiting_team, :event_datetime).with_message("** DOUBLE EVENT **") }

唯一性的默认错误消息是“已经采取”。

答案 1 :(得分:1)

如果您遵循rubocops ImplicitExpect,则可能会使用以下内容:

it { is_expected.to validate(%i[home_team], uniqueness: { scope: [:visiting_team, :event_datetime] }) }

it { is_expected.to validate_uniqueness_of(:home_team).scoped_to(:visiting_team, :event_datetime) }

(请注意,由于原始问题非常古老,因此我没有提供自定义错误消息,因此,与原始问题询问者相比,我希望为Google的访问者提供更多的答案)

答案 2 :(得分:0)

使用新的“期望”语言

let(:line) { build(:line) } # if using factory bot, or you could use fixtures
it {expect(line).to validate_uniqueness_of(:home_team).scoped_to(:visiting_team, :event_datetime)  }