Rspec tests on Ruby on Rails
In the tests, I am a complete zero, advise, and it is better to at least start to help with the tests, I really ask.
Tasks_controller.rb
class TasksController < ApplicationController
expose :task, -> {current_user.tasks.find(params[:id])}
expose :active_tasks, -> {current_user.tasks.where(active: false).order('priority ASC')}
expose :completed_tasks, -> {current_user.tasks.where(active: true).order('priority ASC')}
def index
render json: {active: active_tasks, completed: completed_tasks}, status: 200, each_serializer: TasksSerializer
end
def show
render json: task, status: 200, each_serializer: TaskSerializer
end
def create
task = current_user.tasks.create(task_params)
render json: task.id, status: 201, each_serializer: TaskSerializer
end
def update
if task.update(task_params)
render json: task, status: 200
else
render json: task.errors, status: 422, each_serializer: TaskSerializer
end
end
def destroy
if task.destroy
return head(:ok)
else
return head(:bad_request)
end
end
def batch_destroy
tasks = current_user.tasks.where(id: params[:ids]).destroy_all
end
private
def task_params
params.require(:task).permit(:title, :description, :priority, :due_date, :active)
end
end
Task.rb
class Task < ApplicationRecord
belongs_to :user
validates :title, presence: true,
length: {
maximum: 10
}
validates :description, presence: true,
length: {
minimum: 4,
maximum: 10
}
validates :priority, presence: true
end
1 answers
Good time of day.
Rspec tests start with a theory of what to test and why. I always have these links "at hand":
About testing with Rspec
About proper testing
About the accompanying...
In short, tests using Rspec or any other library will help you go to the console or browser much less often to make sure that your code works. Each component of the project: model, view, controller, mailer, etc., can be checked for the so-called expected behavior. For example: the controller method (action) should return a certain status in the response, change or not change the number of records in the table, render a certain view. Every aspect of your application can and in most cases should be tested, in other words, "covered by tests".
In a practical sense, it is necessary to prepare the project for testing. To do this, a number of libraries are added to the Gemfile. In my case, the following set "wanders" from project to project:
group :development, :test do
gem 'rspec-rails' # собственно сам RSpec
gem 'factory_bot_rails' # фабрики, которые серьезно упрощают жизнь тестировщика
gem 'database_cleaner' # штука, которая очищает тестовую БД между тестами
gem 'rails-controller-testing' # позволяет тестировать контроллеры чуть в более широком смыслке
end
You need to install the libraries and initialize rspec
bundle install
rails generate rspec:install
Now you can create files with project tests in the /spec
directory. For example for your for the controller TasksController
, a primitive test might look like this:
# /spec/controller/task_controller_spec.rb
require 'rails_helper'
RSpec.describe TaskController, type: :controller do
# группа тестов, которая отвечает за тестирование экшена index
describe "GET #index" do
# тест проверяет что возвращается корретный запрос
it "returns a success response" do
get :index
expect(response).to have_http_status(:ok)
end
# ниже должны быть тесты которые проверяют на рендеринг определенных
# представлений и создание (assigns) определенных экземпляров
it "renders index template" do
end
it "assigns tasks" do
end
end
end
In general, this is a very extensive topic to fit into a short post. Fortunately, there is enough information on the network.
For a sample, you can look at my small project, which has a certain number of tests for models, controllers, and views: