I finally decided to start working on Rspec. It seems that you can do various tests using this. It's amazing. However, it seemed a little tough, so I decided to use online teaching materials. This is Take off Rails.
https://freelance.cat-algorithm.com/lp/take-off-rails
I haven't had enough time these days, so I needed to streamline things. It's a form of buying time with money, which was very good. The information is aggregated and I asked if I didn't understand.
Even so, I've had a lot of trouble, so I'll write it here.
This time, to create spec / models / user_spec.rb
and spec / factories / users.rb
for the existing user model,
$ rails g model user -s
Tried to run. However, an error occurred.
$ rails g model user -s
Running via Spring preloader in process 1605
invoke active_record
The name 'User' is either already used in your application or reserved by Ruby on Rails.
Please choose an alternative or use --force to skip this check and run this generator again.
Apparently the skip option wasn't available. I asked a question, committed all the modified files, then did $ rails g model user --force
and ran $ git restore .
. By doing this, the same effect as skip was obtained.
When I tried to test the create action of the user controller, I got the following error.
Failures:
1) Users POST /users Can create user records
Failure/Error: expect{subject }.to change { User.count }.by(1)
expected `User.count` to have changed by 1, but was changed by 0
# ./spec/requests/users_spec.rb:53:in `block (3 levels) in <main>'
When I searched for the cause, I found that it did not transition to the user # create action. Instead, devise's #create action was being executed.
When I checked with $ rails routes
, the paths of devise # controller and user # controller were the same. I have to change this a little.
It was set as follows.
config/routes.rb
Rails.application.routes.draw do
root to: 'users#index'
devise_for :users
resources :users ,path_names: { create: 'make' } do
resources :plants do
resources :growth_records, shallow: true
end
end
scope 'username' do
resources :users, only: [:create]
end
end
This time, I changed the part of scope
. This eliminates routing conflicts. Part of the test looks like this:
RSpec.describe "Users", type: :request do
#Omission-----
describe "POST /users" do
subject { post('/username/users' ,params: params) }
let(:params){ {user: attributes_for(:user)} }
it "Can create user records" do
expect{subject }.to change { User.count }.by(1)
expect(response).to have_http_status(204)
end
end
#Omission-----
end
The previous post (users_path, params: params)
has been changed to post ('/ username / users', params: params)
.
The world of Rspec is deep. Right now, I'm only conscious of no errors, but I want to think about "what tests are needed and how much" by myself.
After all, programming is fun.
Recommended Posts