这是我的测试代码:
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)>'
我对编写测试相当陌生(尤其是使用 using Rspec
)。只是想找人给我一些关于我做错了什么的建议。