iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0
自我挑戰組

Rails測試寫起乃!!!系列 第 13

Day13 測試寫起乃 - controller test

  • 分享至 

  • twitterImage
  •  

Controller test

主要測在 controller 的 action,基本的 CRUD action,或是一些response是否正確、redirect 網址是否正確為主,可以用 restful http 的動詞來撰寫測試

require 'rails_helper'

RSpec.describe CollectionsController, type: :controller do
  describe 'Get #index' do
    it 'when resource is found' do
      get :index
      collection = create(:collection)
      expect(response.status).to eq 200
      expect(assigns(:collection)).to eq([collection])
    end
  end

  describe 'Post #create' do
    it 'redirect to index when create collection success' do
      post :create, params: { collection: { title: '11', description: '222' } }
      expect(response).to redirect_to(collections_path)
      expect(Collection.count).to eq 1
    end
  end

  describe 'Get #show' do
    let(:collection) { create(:collection) }
    it 'redirect to index when create collection success' do
      get :show, params: { id: collection }
      expect(response).to have_http_status(200)
      expect(response).to render_template(:show)
    end
  end
end


起手式都是以 get 、 post 、 put/patch 、 delete 為主,後方接 :action,若有需要 params,則在最後新增

post :create 為例

post :create => 以 Post 方式打到 :create 的 action

params => 跟你平常新增一筆資料一樣一定會需要params,直接在後方加上參數即可

redirect_to => 其中一種 matchers,期望新增完成後會轉址到index

另外還有

have_http_status => 期望此 response 狀態碼為多少?
你也可以使用 response.status 查看 status_code 為多少

render_template => 期望此 response 會渲染哪一個頁面?

assigns() => 為此 action 的 instance variable,比如寫assigns(:collection)則表示在 index 有一個 @collection

還有更多 matchers 跟應用可以參考這裡

至於 assigns 現在已經被拋棄無法使用了如果你是較新版的 Rails,如果真的要使用的話可以安裝 rails-controller-testing

這篇也有講為何不要在測試上測試 instance variable


上一篇
Day12 測試寫起乃-mock、stub
下一篇
Day14 測試寫起乃-request vs controller test
系列文
Rails測試寫起乃!!!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言