Rails 3.1, RSpec: testing model validations

后端 未结 7 1562
不知归路
不知归路 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:35

    A little late to the party here, but if you don't want to add shoulda matchers, this should work with rspec-rails and factorybot:

    # ./spec/factories/user.rb
    FactoryBot.define do
      factory :user do
        sequence(:username) { |n| "user_#{n}" }
      end
    end
    
    # ./spec/models/user_spec.rb
    describe User, type: :model do
      context 'without a username' do
        let(:user) { create :user, username: nil }
    
        it "should NOT be valid with a username error" do
          expect(user).not_to be_valid
          expect(user.errors).to have_key(:username)
        end
      end
    end
    

提交回复
热议问题