Using shoulda to refactor rspec tests on Rails models

前端 未结 5 2290
闹比i
闹比i 2021-02-14 00:57

After learning about shoulda-matchers by answering another StackOverflow question on attribute accessibility tests (and thinking they were pretty awesome), I decided to try refa

5条回答
  •  时光说笑
    2021-02-14 01:39

    I've found some value in writing tests for the presence of database columns. Here's why:

    1) Writing them keeps me in the rhythm of TDD.
    2) Migrations are usually pretty awesome, until they aren't. I know you're not supposed to edit an existing migration, but when I'm just working on something myself I sometimes do it anyway. And if someone else is working on the same application and changes an existing migration instead of writing a new one, these tests have isolated the problem pretty quickly for me.

    If you get bogged down with too many column names & types you can do something like this to save yourself typing:

    describe User do
    
      describe 'database' do 
    
        describe 'columns' do 
    
          %w[reset_password_sent_at remember_created_at current_sign_in_at 
            last_sign_in_at confirmed_at confirmation_sent_at 
            created_at updated_at
            ].each do |column|
            it { should have_db_column(column.to_sym).of_type(:datetime) }
          end
        end
    
        describe 'indexes' do 
    
          %w[confirmation_token email reset_password_token
          ].each do |index|
            it { should have_db_index(index.to_sym).unique(true)}
          end
        end
      end  
    end
    

    Hope that helps.

提交回复
热议问题