Then, bundle install
Generating the serializer for lesson model : rails g serializer lesson
After that, you can specify attributes you want render :
attributes :id, :title, :description, :created_at
Now, it's easy because we have no association.
Routes
We use the keyword ressources in the route.rb file :
resources :lessons, except: [:new, :edit]
Testing the last step with rails routes
Controller
Create a controller with this ressource. As read, ApplicationController is the right controller for API.
Error :
We want that an error raises up when params aren't valid. create!() permit that : if validation doesn't work, ActiveRecord::RecordInvalid: Validation failed: raises. Place that in application.rb file :
# Two errors catched : RecordInvalid and ParameterMissing
rescue_from ActiveRecord::RecordInvalid, ActionController::ParameterMissing, with: :show_errors
def show_errors(exception)
render json: exception, status: 403
end
Render :
To return, use render json: object, status number.
Replace with the correct object who has a serializer. Add the correspondent status (the number or the name).
Test controller :
Some tips :
creating some lessons with FactoryBot.create_list(:lesson, 2). But to test index method, no need creates few dozens of lessons. Just two are sufficient.
it { should route(:get, '/lessons').to(action: :index) } to test each route with the url and the name of method in the controller.
expect(response.code).to eq("200") to test the response code.
use variables with let (lazy utilisation) and let! (behavior like before)
use subject
describing with keywords describe which contains context 's
Controller
Serializer :
Add Serializer gem in Gemfile :
Then,
bundle install
Generating the serializer for lesson model :rails g serializer lesson
After that, you can specify attributes you want render :Now, it's easy because we have no association.
Routes
We use the keyword ressources in the
route.rb
file :Testing the last step with
rails routes
Controller
Create a controller with this ressource. As read, ApplicationController is the right controller for API.
Error :
We want that an error raises up when params aren't valid.
create!()
permit that : if validation doesn't work,ActiveRecord::RecordInvalid: Validation failed:
raises. Place that inapplication.rb
file :Render :
To return, use
render json: object, status number
. Replace with the correct object who has a serializer. Add the correspondent status (the number or the name).Test controller :
Some tips :
FactoryBot.create_list(:lesson, 2)
. But to test index method, no need creates few dozens of lessons. Just two are sufficient.it { should route(:get, '/lessons').to(action: :index) }
to test each route with the url and the name of method in the controller.expect(response.code).to eq("200")
to test the response code.before
)subject
describe
which containscontext
'sCloses #9