Rails 3.1, RSpec: testing model validations

后端 未结 7 1545
不知归路
不知归路 2021-01-30 03:51

I have started my journey with TDD in Rails and have run into a small issue regarding tests for model validations that I can\'t seem to find a solution to. Let\'s say I have a U

7条回答
  •  生来不讨喜
    2021-01-30 04:31

    Like @nathanvda said, I would take advantage of Thoughtbot's Shoulda Matchers gem. With that rocking, you can write your test in the following manner as to test for presence, as well as any custom error message.

    RSpec.describe User do
    
      describe 'User validations' do
        let(:message) { "I pitty da foo who dont enter a name" }
    
        it 'validates presence and message' do
         is_expected.to validate_presence_of(:name).
          with_message message
        end
    
        # shorthand syntax:
        it { is_expected.to validate_presence_of(:name).with_message message }
      end
    
    end
    

提交回复
热议问题