(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