Вот мой тестовый код:Rspec/Rails и тестирование validates_uniquess_of с размахом
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
). Просто ищем кого-то, чтобы дать мне несколько советов о том, что я делаю неправильно.
Большое спасибо за вашу помощь! – dennismonsewicz
Просто для исправления части вышеперечисленного. Первый валидационный сбой должен работать с «it {должен validate_uniqueness_of (: name) .scoped_to (: user_id) .with_message ('уже существует')}" Обратите внимание на разницу в размещении вызова .with_message – donden1