2

ここに私のテストコードがあります:

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)。私が間違っていることについてアドバイスをくれる人を探しているだけです。

4

1 に答える 1

8
  1. 最初の検証の失敗:
    モデルで、rspec が一意性検証のために生成するデフォルト メッセージをオーバーライドしました。したがって、このような検証をテストする際には、shoulda の「with_message」オプションを使用する必要があります。したがって、テストは次のようになり
    ます。

  2. 2 番目の検証の失敗:
    2 番目の例のように一意性検証仕様を自分で作成する場合、データベースに既に存在する 1 つのレコードを作成し、同様のパラメーターで 2 番目のレコードを作成する必要があります。次に、この重複レコードは無効になり、予想どおりエラーが発生します。
    したがって、before(:each) ブロックでは、最初の @classroom レコードを構築するだけでなく、データベースに保存します

于 2013-04-23T08:06:13.943 に答える