Rspec / Rails并使用范围测试validates_uniquess_of

时间:2013-04-22 20:22:40

标签: ruby-on-rails-3 rspec tdd shoulda

这是我的测试代码:

require 'spec_helper'

describe Classroom, focus: true do

  let(:user) { build_stubbed(:user) }

  describe "associations" do
    it { should belong_to(:user) }
  end

  describe "validations" do
    it { should validate_presence_of(:user) }
    it { should validate_uniqueness_of(:name).scoped_to(:user_id) }

    context "should create a unique classroom per user" do

      before(:each) do
        @class = build_stubbed(:classroom, name: "Hello World", user: user)
        @class2 = build_stubbed(:classroom, name: "Hello World", user: user)
      end

      it "should not create the second classroom" do
        @class2.should have(1).errors_on(:name)
      end
    end
  end

  describe "instance methods" do

    before(:each) do
      @classroom = build_stubbed(:classroom)
    end

    describe "archive!" do

      context "when a classroom is active" do
        it "should mark classroom as inactive" do
          @classroom.stub(:archive!)
          @classroom.active.eql? false
        end
      end

    end

  end

end

这是我的课堂模型:

class Classroom < ActiveRecord::Base
  attr_accessible :user, :name

  belongs_to :user

  validates :user, presence: true
  validates_uniqueness_of :name, scope: :user_id, message: "already exists"

  def archive!
    update_attribute(:active, false)
  end
end

当我运行测试时,我收到以下错误:

1) Classroom validations 
     Failure/Error: it { should validate_uniqueness_of(:name).scoped_to(:user_id) }
       Expected errors to include "has already been taken" when name is set to "arbitrary_string", got errors: ["user can't be blank (nil)", "name already exists (\"arbitrary_string\")"]
     # ./spec/models/classroom_spec.rb:13:in `block (3 levels) in <top (required)>'

  2) Classroom validations should create a unique classroom per user should not create the second classroom
     Failure/Error: @classroom2.should have(1).errors_on(:name)
       expected 1 errors on :name, got 0
     # ./spec/models/classroom_spec.rb:24:in `block (4 levels) in <top (required)>'

我是编写测试的新手(特别是使用Rspec时)。只是找人给我一些关于我做错的建议。

1 个答案:

答案 0 :(得分:8)

  1. 首次验证失败
    在您的模型中,您已覆盖了rspec为唯一性验证生成的默认消息。因此,在测试此类验证时,您必须使用shoulda的'with_message'选项。 所以测试应该像是   “它{should validate_uniqueness_of(:name).scoped_to(:user_id)} .with_message('已存在')”

  2. 第二次验证失败:
    当您在第二个示例中自己编写唯一性验证规范时,您必须创建一条已存在于数据库中的记录,并构建具有类似参数的第二条记录。然后,此重复记录将无效,并且会出现预期的错误 因此,在之前(:每个)块中,将第一个@classroom记录保存在数据库中而不是仅仅构建它