【问题标题】:shoulda matchers should validate_uniqueness_of failing with scope应该匹配器应该 validate_uniqueness_of 在范围内失败
【发布时间】:2013-04-28 21:32:50
【问题描述】:

我有 3 个模型,用户、游戏和玩家。用户和游戏之间基本上是多对多的关系,玩家作为连接表,除了玩家有其他信息,所以它有自己的模型。

玩家需要一个独特的游戏ID和用户ID组合,所以我试着在玩家中说:

validates_uniqueness_of :user_id, :scope => :game_id

然后在我的规范中,我说(使用应该匹配器):

it { should validate_uniqueness_of(:user_id).scoped_to(:game_id)}

这里是玩家定义的关系:

belongs_to :game, :inverse_of => :players
belongs_to :user, :inverse_of => :players

但我在该规范上收到 ActiveRecord::statementinvalid 错误

ActiveRecord::StatementInvalid: Mysql2::Error: Column 'game_id' cannot be null: INSERT INTO `players` ETC...

知道出了什么问题吗?

【问题讨论】:

    标签: ruby-on-rails rspec shoulda


    【解决方案1】:

    这是一个known issue。如果作用域字段依赖于模型并且也设置为:null => false,则会出现此错误。

    另外,请查看rails Column cannot be null:

    【讨论】:

    【解决方案2】:

    虽然这是一个已知问题,但有办法解决。

    如果您先创建一条记录,然后测试唯一性验证,它将起作用。

    所以,不要简单地写

    it { should validate_uniqueness_of(:user_id) }
    

    你可以写

    it do
      FactoryGirl.create(:player)
      should validate_uniqueness_of(:user_id)
    end
    

    唯一性验证规范将起作用。

    参考:http://rubydoc.info/github/thoughtbot/shoulda-matchers/master/frames

    【讨论】:

    • it { expect(create(:label)).to validate_uniqueness_of(:value).scoped_to(:question_id) } 使用 rspec3 语法将所有内容放在一条平滑线上。
    【解决方案3】:

    您可以阅读官方源代码警告here中提到的问题和解决方案

    一种解决方案是:

    describe Player do
      describe "validations" do
        it do
          expect(Player.new(game_id: 1)).
            to validate_uniqueness_of(:user_id).
            scoped_to(:game_id)
        end
      end
    end
    

    【讨论】:

      【解决方案4】:

      对于今天遇到此问题的人来说,这里有一个更新的解决方案。

      添加一个主题,以便测试有一个带有值的记录。

      另外,请注意较新的 RSpec 语法。

          subject { create(:player) }
      
          it { is_expected.to validate_uniqueness_of(:user_id).scoped_to(:game_id)}
      

      查看the file on github了解更多信息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多