rails 184.108.40.206 ruby 2.6.5
・ Purpose of unit testing of model, what to test ・ Preparation for RSpec installation (installation of necessary gems) I will explain in this way.
In conclusion, to keep the code maintainable. Obviously, you don't want bugs in your released application. There may be an unexpected oversight of manually confirming that no bugs occur, so if you write a reliable test, even if there is a change in the code, you can manually say "OK because the test passed" This means that you can save the trouble of checking the behavior.
① Validation When saving values in the database, define rules such as "Do not save empty values", "Maximum number of characters", "Save only numbers", "Convert uppercase letters to lowercase letters". This is because it is not desirable for database design to store non-regular values. Model validation is a way to define this rule on the rails side. Therefore, testing the model checks that validation is working properly.
② Method You can define your own methods for the model to represent the behavior of the model. This is also difficult to test manually, so incorporate it into the test.
③ Other The role of the model is "definition of association". Since the association itself is defined on the rails side, it seems that it is not necessary to test it in particular, but when deleting the data of a certain model, whether the related model is deleted is also included in the test.
First, let's start with the RSpec settings. Execute the following command.
% bin/rails generate rspec:install
Then the generator will generate the rspec configuration file and save folder as shown below.
Running via Spring preloader in process 28211 create .rspec create spec create spec/spec_helper.rb create spec/rails_helper.rb
Open the .rspec file and make the following changes: This makes it possible to output a clean display of the test execution results.
--require spec_helper --format documentation
Next is the gem installation.
group :development, :test do gem 'factory_bot_rails' gem 'rspec-rails', '~> 4.0.0' #Omitted below end group :development do gem 'spring-commands-rspec' #Omitted below end
The final'spring-commands-rspec' is a binstub for the RSpec test runner. This will benefit from spring, which speeds up application startup. Ignore it if you don't want to use Spring. Finally, there is one more item to set. Let's set Rails so that when you execute the rails g command, a spec file for RSec will also be created. Also, avoid generating unnecessary files. Open config / application.rb and edit it as follows.
class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.generators do |g| g.test_framework :rspec, view_specs: false, helper_specs: false, routing_specs: false end end
This completes the settings for deploying RSpec!