2013-04-22 117 views
2

这里是我的测试代码: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)相当陌生。只是想找人给我一些关于我做错什么的建议。

回答

8
  1. 首先验证失败
    在你的模型,你已经覆盖该rspec的产生的唯一性验证默认的消息。因此,在测试这种验证时,您必须使用shoulda的'with_message'选项。 所以测试应该是这样
    “它{应当validate_uniqueness_of(:名称).scoped_to(:USER_ID)} .with_message( '已经存在')”

  2. 的第二次确认失败:
    当如第二个示例中那样编写唯一性验证规范,则必须创建一个已存在于数据库中的记录,并使用相似的参数构建第二条记录。那么这个重复的记录将不会有效,并且会按预期发生错误。
    所以在前(:每个)块,保存在数据库中的第一@classroom记录,而不只是建立它

+0

非常感谢你的帮助! – dennismonsewicz 2013-04-23 14:44:51

+0

只是为了纠正上面的错误。第一个验证失败应该与 一起使用“it {should validate_uniqueness_of(:name).scoped_to(:user_id).with_message('already exists')}” 注意.with_message调用的定位不同 – donden1 2014-09-27 15:05:49