(1)FactoryGirl.attributes_for(:contact)生成hash正則表達式
(2)assigns(:variable_name)方法,能夠理解爲接受action處理後放回的@variable_name賦值給一個局部變量數組
(3)控制器測試的關鍵點:ruby
(1)測試GET請求的動做(index、show、new、edit):返回值是不是咱們期待的(expect(assigns(:variable_name)).to eq variable,當返回值是一個數組而且不要求數組順序時用match_array(array),要求順序用eq;期待返回是一個新對象能夠用be_a_new(Class));渲染的頁面是否是咱們期待的(expect(response).to render_template :action);例:session
describe 'GET #show' do it 'assigns the requested contact to @contact' do contact = create(:contact) #FactoryGirl.create(:contact)縮略形式 get :show, id: contact expect(assigns(:contact)).to eq contact end it 'renders the :show template' do contact = create(:contact) get :show, id: contact expect(response).to render_template :show end end
(2)測試POST請求(create):和GET請求思路類似,只是參數須要Hash,須要使用attributes_for(),還須要分爲參數合法以及不合法兩種狀況,create成功期待數據條數變化,例:post
expect{ post :create, contact: attributes_for(:contact) }.to change(Contact, :count).by(1)
將HTTP請求放入expect塊中,是爲了延遲執行,檢測的值會在請求執行先後執行兩次,來驗證變化測試
(3)測試PATCH請求(update):分爲參數合法與不合法兩種狀況,分別驗證返回數據是否有,以及是否修改爲功,以及渲染的模板;spa
(4)測試DELETE請求(destroy):change(Class, :count).by(-1),redirect_to code
(5)測試非CRUD動做:有返回值驗證返回值,或驗證數據條數變化;驗證render頁面對象
(6)測試不輸出HTML的控制器:能夠驗證響應頭的Content-Type(expect(response.headers['Content-Type']).to have_content 'text/csv');能夠驗證相應體是否含有特定的內容(expect(response.body).to have_content '');have_content是Capybara提供的方法,也能夠使用rails-rspec提供的match()參數爲正則表達式get
(7)測試須要登錄或須要權限的action時,能夠用beafore在測試前將登錄信息放入session