主要测在 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
<<: 30天零负担轻松学会制作APP介面及设计【DAY 04】
终於最後一天,照惯例大家都在这里写後记吧~ 三年前第一次知道铁人赛,就是以社群身份去参加了颁奖典礼X...
使用 Firebase 专案串接 GA4 资源,提升 App 绩效 过往无法一探究竟的技术过程,现在...
工具介绍 Skipfish是一个google开发的网页安全扫描工具,主要特色如下 纯C打造的高效工具...
之前我们做的所有操作,都是在 Jupyter Notebook 进行,没有进行资料储存的动作,所以只...
Microsoft Office 专家 - MO-300 考试对您的职业生涯来说是一个非常显着的提升...