Rails 3.1 Rspec Creating test case validate field for Model

前端 未结 2 1233
梦毁少年i
梦毁少年i 2021-02-10 14:49

I\'m trying to create a test case for User model. Basically, it will validate first_name and last_name to be present.

What I am trying to do is to check whether the err

2条回答
  •  鱼传尺愫
    2021-02-10 15:23

    RSpec supports the notion of an "implicit" subject. If your first argument to the "describe" block is a class, RSpec automatically makes an instance of that class available to your specs. See http://relishapp.com/rspec/rspec-core/v/2-6/dir/subject/implicit-subject.

    require 'spec_helper'
    
    describe User do
    
      it "must have a first name" do    
        subject.should have(1).error_on(:first_name)
      end
    
      it "must have a last name" do
        subject.should have(1).error_on(:last_name)
      end
    end
    

    which results in RSpec output (if using --format documentation) of:

    User
      must have a first name
      must have a last name
    

    You can abbreviate it even further if you are content with the RSpec output defaults:

    require 'spec_helper'
    
    describe User do
      it { should have(1).error_on(:first_name) }
      it { should have(1).error_on(:last_name) }
    end
    

    which results in:

    User
      should have 1 error on :first_name
      should have 1 error on :last_name
    

提交回复
热议问题