【问题标题】:Rails with Shoulda and multiple scopes uniques fails tests具有 Shoulda 和多个范围唯一性的 Rails 未通过测试
【发布时间】:2019-01-16 05:22:27
【问题描述】:

我在这里做错了什么?我很确定实际代码是正确的,但我的测试有问题这只是应该匹配器的失败吗?还是我只是错过了什么?

require 'rails_helper'

RSpec.describe Game, type: :model do
  subject { create :game }

  it { should belong_to(:home_team).class_name('Team') }
  it { should belong_to(:away_team).class_name('Team') }

  it { should validate_uniqueness_of(:start_date).scoped_to(:home_team_id) }
  it { should validate_uniqueness_of(:start_date).scoped_to(:away_team_id) }
end
class Game < ActiveRecord::Base
  belongs_to :home_team, class_name: 'Team'
  belongs_to :away_team, class_name: 'Team'

  validates_uniqueness_of :start_date, scope: :home_team_id
  validates_uniqueness_of :start_date, scope: :away_team_id
end
   Expected Game to validate that :start_date is case-sensitively unique
   within the scope of :home_team_id, but this could not be proved.
     Given an existing Game whose :start_date is ‹Fri, 31 Aug 2018 05:24:25
     UTC +00:00›, after making a new Game and setting its :start_date to
     ‹Fri, 31 Aug 2018 05:24:25 UTC +00:00› as well and its :home_team_id
     to a different value, ‹5›, the matcher expected the new Game to be
     valid, but it was invalid instead, producing these validation errors:

     * start_date: ["has already been taken"]

【问题讨论】:

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


    【解决方案1】:

    对不起,我之前的回答不正确。看起来应该不能自动处理你的案子。它更改了home_team_id,并期望游戏有效,但它仍然具有相同的away_team_id,因此您需要手动验证它

    it 'validates uniqueness for both teams' do
      team1 = create :team
      team2 = create :team
      team3 = create :team
      game = create :game, home_team: team1, away_team: team2
      game1 = build :game, home_team: team1, away_team: team3
      game2 = build :game, home_team: team3, away_team: team2
      game3 = build :game, home_team: team2, away_team: team1
    
      expect(game).to be_valid
      expect(game1).not_to be_valid
      expect(game2).not_to be_valid
      expect(game3).to be_valid
    end
    

    【讨论】:

      猜你喜欢
      • 2012-03-28
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 2011-10-23
      相关资源
      最近更新 更多