唯一性验证测试

时间:2018-06-13 18:17:32

标签: ruby-on-rails postgresql activerecord rspec

运行Rails 4.2.8

我添加了一个外键为user_id的新模型。虽然功能上一切似乎都运行良好,但当我运行测试确认user_id的唯一性验证时,我收到ActiveRecord::InvalidForeignKey错误。详情如下。

迁移

create_table :standard_accounts do |t|
  t.timestamps null: false
  t.references :user, index: true, foreign_key: true
end

模型

class StandardAccount < ActiveRecord::Base
  belongs_to :user

  validates_presence_of :user_id  
  validates_uniqueness_of :user_id
end

structure.sql(由于烦人的原因,我们使用的是strucuture.sql而不是架构)

ALTER TABLE ONLY public.standard_accounts
  ADD CONSTRAINT fk_rails_6bc98ede2c FOREIGN KEY (user_id) REFERENCES public.users(id);

测试

RSpec.describe StripeStandardAccount, type: :model do
  it { should belong_to(:user) }
  it { should validate_presence_of(:user_id) }
  it { should validate_uniqueness_of(:user_id) }
  ...

测试失败

1) StandardAccount should validate that :user_id is case-sensitively unique
 Failure/Error: it { should validate_uniqueness_of(:user_id) }

 ActiveRecord::InvalidForeignKey:
   PG::ForeignKeyViolation: ERROR:  insert or update on table "standard_accounts" violates foreign key constraint "fk_rails_6bc98ede2c"
   DETAIL:  Key (user_id)=(0) is not present in table "users".
   : UPDATE "standard_accounts" SET "user_id" = $1, "updated_at" = $2 WHERE "standard_accounts"."id" = $3
 # ./spec/models/standard_account_spec.rb:9:in `block (2 levels) in <top (required)>'
 # ------------------
 # --- Caused by: ---
 # PG::ForeignKeyViolation:
 #   ERROR:  insert or update on table "standard_accounts" violates foreign key constraint "fk_rails_6bc98ede2c"
 #   DETAIL:  Key (user_id)=(0) is not present in table "users".

我想我可以编辑迁移并删除foreign_key: true位(这可能是在structure.sql中创建外键约束),但这是由Rails默认生成器添加的,而我是&#39 ;我不确定它的目的是什么,似乎这里有其他错误,因为这应该按原样运作。

2 个答案:

答案 0 :(得分:2)

解决此问题的方法是在运行shoulda测试之前,先创建StripeStandardAccount对象的实例 。例如:

  # Step 1
  # If you are using FactoryBot (note: you need to use "!" with your "let")
  let!(:stripe_standard_account) { create(:stripe_standard_account) }

  # If you're not using FactoryBot
  StripeStandardAccount.create(your-required-params-go-here)

  # Step 2
  # Then run your shoulda_matcher test
  it { should validate_uniqueness_of(:user_id) }

这是因为您的测试用例需要一个现有实例才能与其正在创建的实例进行比较。您不能询问对象的单个实例是否唯一。 https://github.com/thoughtbot/shoulda-matchers/issues/682#issuecomment-78124438

答案 1 :(得分:0)

事实证明这实际上是由于shoulda-matchers库中的错误。我能够使用this approach来解决它。