Rails 3.1 Rspec Creating test case validate field for Model

前端 未结 2 1235
梦毁少年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:39

    You can test by simply doing this as well:

    describe 'validations' do
      it { should validate_presence_of :firstname }
      it { should validate_presence_of :lastname  }
    end
    

    Take a look at the shoulda matchers for all such standard Rails Validation. This way is not just more concise but also takes care of the positive case. Meaning you then dont need to test the scenario mentioned below:

    it "passed validations when first_name is set"
      user = User.create(:firstname => 'f', :lastname => 'l')
      user.errors[:first_name].should be_empty
      user.errors[:last_name].should be_empty
    end
    

提交回复
热议问题