【问题标题】:Rspec testing of validates_uniqueness_of passes when it should failvalidates_uniqueness_of 的 Rspec 测试在应该失败时通过
【发布时间】:2014-10-06 18:01:13
【问题描述】:

我对 Rspec 测试还很陌生,这非常令人沮丧。

我有一个模型,它使用 validates_uniqueness_of 来防止创建重复条目。 (我知道这不能保证,首选方法是使用数据库级别的约束,但目前不相关)。

问题是我的 Rspec 测试似乎表明可以在表中创建 2 个具有相同 user_id 和 board_id 的条目,即使在实践中,在控制台和应用程序本身中,这无法完成。

models/moderator_join.rb

class ModeratorJoin < ActiveRecord::Base
  belongs_to :user
  belongs_to :board

  validates :user_id, presence: true
  validates :board_id, presence: true

  validates_uniqueness_of :user_id, scope: :board_id, message: "is already a moderator of that board."
end

spec/models/moderator_join_spec.rb

describe ModeratorJoin do
  let(:user) { create(:user) } // Create with FactoryGirl
  let(:board) { create(:board) } // Create with FactoryGirl
  let(:join) { ModeratorJoin.create(user: user, board: board) }

  subject { join }

  it { should be_valid } // Test passes 
  its(:id) { should_not eq nil } // Test passes
  its(:user) { should eq user } // Test passes
  its(:board) { should eq board } // Test passes

  describe "user/board pairs" do
    let(:join2) { ModeratorJoin.new(user: user, board: board) }

    it "must be unique" do
        expect(join2).to_not be_valid // TEST FAILS
    end
  end
end 

控制台输出

Failures:
1) ModeratorJoin user/board pairs must be unique
Failure/Error: expect(join2).to_not be_valid
expected #<ModeratorJoin id: nil, user_id: 121, board_id: 1, created_at: nil, updated_at: nil> not to be valid

 # ./spec/models/moderator_join_spec.rb:39:in `block (3 levels) in <top (required)>'

【问题讨论】:

  • 你说它应该失败的时候它通过了,但你显示的是失败?

标签: ruby-on-rails-4 rspec validates-uniqueness-of


【解决方案1】:

我认为(现在无法检查自己)subject 未在您的测试中执行。试试这个变种

it "must be unique" do
  subject
  expect(join2).to_not be_valid // TEST FAILS
end

【讨论】:

  • 测试通过了!但我不知道为什么......我认为 join 对象在“必须是唯一的”测试中是可见的,因为它是在开始时声明的。
  • “可见”和“执行”是不同的东西。 subject, let 有“惰性”加载策略。如果它没有被调用 - 它不会被执行。想法被描述here
  • 啊!当然!我忘记了延迟加载。因此,另一种解决方案是使用 let! 而不是 let。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多