shoulda matchers should validate_uniqueness_of failing with scope

你。 提交于 2019-12-08 15:24:15

问题


I have 3 models, user, game, and player. There's basically a many to many relationship between users and games, with players as the join table, except players have other info so it has its own model.

A player needs a unique combo of game id and user id, so I tried to say in player:

validates_uniqueness_of :user_id, :scope => :game_id

and then in my spec, I said (using shoulda matchers):

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

here are the relationships the player defines:

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

yet I'm getting an ActiveRecord::statementinvalid error on that spec

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

Any idea what's going wrong?


回答1:


It is a known issue. It gives this error if the scoped field is dependent on the model and is also set to :null => false.

Also, do have a look at rails Column cannot be null:




回答2:


While this is a known issue, there is a way around it.

If you first create a record and then test the uniqueness validation, it will work.

So, instead of simply writing

it { should validate_uniqueness_of(:user_id) }

You can write

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

And the uniqueness validation spec will work.

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




回答3:


You can read about the issue and solutions mentioned in the official source code caveat here

One solution is:

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:


For people having this issue today here is a newer solution.

Add a subject so that the tests have a record with values.

Also, note the newer RSpec syntax.

    subject { create(:player) }

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

Check out the file on github for more info



来源:https://stackoverflow.com/questions/16268146/shoulda-matchers-should-validate-uniqueness-of-failing-with-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!