Top #10 Xem Nhiều Nhất Cách Viết Test Case Api Mới Nhất 7/2022 # Top Like | Hanoisoundstuff.com

— Bài mới hơn —

Tiếp theo Cách tạo API với Rails (phần 1)

Mình sẽ hướng dẫn cách test căn bản cho API mình tạo. Thật ra mà nói thì mình phải viết test trước khi làm nhưng mà để tránh việc gây khó hiểu nên mình xin mạn phép đảo ngược qui trình.

Để thuận lợi hơn cho việc viết test case mình sử dụng gem rspec-rails

Test case thuộc tính của model mình đã tạo

Để dễ dàng hơn trong việc viết test case mình sử dụng thêm 2 gem:

  • Gem factory_girl_rails để tạo fixture data
  • Gem shoulda
  • Nhớ bundle install lại sau khi add gem

Chúng ta tạo lại model traveler

rails g model traveler first_name:string last_name:string birthday:datetime gender:string

Bây giờ cấu trúc app của chúng ta sẽ xuất hiện thêm phần này ( màu xanh lá cây)

Tạo fixture data

Vào file sau spec/factories/travelers.rb để kiểm tra lại fixture data mà FactoryGirls đã tạo. Mình sẽ edit lại một tí ( dựa vào gem ffake )

FactoryGirl.define do factory :traveler do first_name { FFaker::Name.first_name } last_name { FFaker::Name.last_name } birthday { FFaker::IdentificationESCO.expedition_date } gender { FFaker::Gender.maybe } end end

Test các thuộc tính của model

Bạn tạo model cho traveler và test cho traveler nên bạn sẽ viết test case tại file traveler_spec.rb

Vào file sau spec/models/traver_spec.rb để viết test case

require ‘rails_helper’ describe Traveler do before { @traveler = FactoryGirl.build(:traveler) } subject { @traveler } it { should respond_to(:first_name) } it { should respond_to(:last_name) } it { should respond_to(:gender) } it { should respond_to(:birthday) } end

Kiểm tra kết quả của test case

Tại terminal bạn gõ theo cấu trúc rspec **đường đẫn file muốn test**

rspec spec/models/traveler_spec.rb

Test respond trả về khi request api

  • Test response code trả về thành công là 200
  • Test data trả về gồm những thành phần gì

require ‘spec_helper’ describe V1::TravelersController do before do @traveler = FactoryGirl.create :traveler get “/v1/travelers”, format: :json end it ‘return traveler information’ do traveler = JSON.parse(response.body, symbolize_names: true).first expect(traveler).to eql @traveler.last_name expect(traveler.to_s.to_i).to eql @traveler.birthday.to_s.to_i end it ‘response code’ do expect(response).to have_http_status(200) end end

Run lệnh này để kiểm tra kết quả

rspec spec/requests/v1/travelers_controller_spec.rb

Yah! đã xong

— Bài cũ hơn —