Search code examples
ruby-on-railsrubytestingminitestshoulda

Refactoring test with shoulda, the minitest way


I was browsing shoulda matchers and context in order to refactor some text and make them more coincise and readable, but thorough, the documentation I could not find how to test this in specific:

(I'm following Hartl tutorial, and I'm trying to refactor in the Minitest way, not Rspec)

micropost_model

default_scope -> { order(created_at: :desc) }

has_one_attached :image

&

validates :image,   content_type: { in: %w[image/jpeg image/gif image/png],
                                      message: 'must be a valid image format' },
                    size: { less_than: 5.megabytes,
                            strong textmessage: 'should be less than 5MB' }

this:

user_test

user_model

attr_accessor :remember_token, :activation_token, :reset_token

before_save   :downcase_email
before_create :create_activation_digest

this:

routes

  resources :account_activations, only: [:edit]
  resources :password_resets,     only: %i[new create edit update]
  resources :microposts,          only: %i[create destroy]
  resources :relationships,       only: %i[create destroy]

Solution

  • In general here are the ways you can test the pieces you've posted:

    • shoulda-matchers will soon have a have_one_attached matcher you can use to test has_one_attached.
    • The validations you posted for Micropost come from Paperclip and Paperclip provides matchers you can use in your tests.
    • You can use the validation matchers in Shoulda in place of the first several tests in user_test — for instance, should validate_presence_of(:email), should validate_length_of(:email).is_at_most(255), etc.
    • Shoulda doesn't provide any facility to test authentication- or callback-related code — you will have to take a look at what your User model is doing and write tests around the logic manually. Judging by the code snippet you posted, this would probably consist of making an instance of your model, setting some attributes, saving the model, and asserting that certain attributes are set.
    • There is a way to test routes using Shoulda using the route. I will say about this that you will probably get better mileage per test in writing an integration or system test which exercises the functionality that is accessible via the route rather than test the route directly. But at least that matcher is there should you want that level of granularity.

    Hope that helps — let me know if you need more help.