What can We do in a Model Test?

Get an overview of the model-view-controller and what we’ll do in this chapter.

Model-view-controller

A standard Rails application uses a design pattern called MVC, which stands for model-view-controller. Each of the three sections in the MVC pattern is a separate layer of code, which has its responsibilities and communicates with the other layers as infrequently as possible. In Rails, the model layer contains both business and persistence logic, with the persistence logic handled by ActiveRecord. Typically, all of our ActiveRecord objects will be part of the model layer, but not everything in the model layer is necessarily an ActiveRecord object. The model layer can include various services, value objects, or other classes that encapsulate logic and use ActiveRecord objects for storage.

What we’ll do in this chapter?

We’ll start the tour of testing the Rails stack with the model layer because model tests have the fewest dependencies on Rails-specific features and are often the most comfortable place to start testing our application. Standard Rails model tests are very nearly vanilla RSpec. Features specific to Rails include a few new matchers and the ability to set up initial data.

We’ll also talk about testing ActiveRecord features such as associations and models. We’ll discuss separating logic from persistence and why that can be a valuable practice for both testing and application development.

What can we do in a model test?

An RSpec file in the spec/models directory is automatically of type: :model, which doesn’t give much new behavior. An add-on gem called rspec-activemodel-mocks, which the RSpec core team maintains, includes some mock-object tools specific to use with ActiveModel.

What should we test in a model test?

Models.

What makes a good set of model tests?

Back to serious business. There are several different, sometimes conflicting, goals for tests. It’s hard to know where to start the TDD process, how many tests to write, and when we’re done. The classic description of the process, which is“write a simple test, make it pass, then refactor,” doesn’t provide much affirmative guidance or direction for the more extensive process of adding a feature.

Get hands-on with 1200+ tech skills courses.