测试自定义Rails验证的正确方法

时间:2017-06-15 16:07:11

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

我有4个模特

class A < ApplicationRecord
  has_many :b
  has_many :c
end

class B < ApplicationRecord
  belongs_to :a
  has_many :c, through: :d
end

class C < ApplicationRecord
  belongs_to :a
  has_many :b, through: :d
end

class D < ApplicationRecord
  belongs_to :a
  belongs_to :b
end

我想在制作d模型时测试bc都属于同一个a。问题是:

对于rspec来说,测试这个简单的“有效案例/无效案例”测试的最佳方法如下:

it "should be valid if both B and C have the same A" do
  a1 = A.first
  b1 = a1.bs.first
  c1 = a1.cs.first

  d1 = D.new(b: b1, c: c1)
  expect(d1.valid?).to be_truthy
end

it "should be invalid if B and C have different A's" do
  a1, a2 = A.first(2)
  b1 = a1.bs.first
  c1 = a2.cs.first

  d1 = D.new(b: b1, c: c1)
  expect(d1.valid?).to be_falsey
end
#assuming that there is test data in the test database 

还是有更好/更完整的方法来测试这种验证是否正在发生?

0 个答案:

没有答案