22

我的 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)>'

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

4

3 回答 3

46

我认为你需要这样做让它通过

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

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

于 2013-05-08T08:15:27.597 回答
2

如果您关注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) }

(请注意,我没有包含自定义错误消息,因为原始问题已经很老了,我倾向于通过这个答案帮助来自谷歌的访问者,而不是原始问题提问者)

于 2020-04-15T09:49:41.603 回答
1

使用新的“期望”行话

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)  }
于 2020-10-15T05:24:06.373 回答