因為 let 有 lazy load 特性,只在測項第一次用到該 variable 時被執行,並且會 cache 直到該測項結束
這個技巧在產生 database 內容以測試 query 和 scope 時十分好用
Controller Specs
Examples
12345678910111213141516
require'rails_helper'describeTeamsController,:type=>:controllerdodescribe"GET index"doit"assigns @teams"doteam=Team.createget:indexexpect(assigns(:teams)).toeq([team])endit"renders the index template"doget:indexexpect(response).torender_template("index")endendend
Matchers
render_template
1
expect(response).torender_template(:new)
redirect_to
1
expect(response).toredirect_to(location)
have_http_status
12345678910
expect(response).tohave_http_status(:created)# success 就有四種寫法 XDexpect(response).tohave_http_status(200)expect(response.status).toeq(200)expect(response).tohave_http_status(:ok)expect(response).tohave_http_status(:success)# page not foundexpect(response).tohave_http_status(404)
require"rails_helper"describePost,:type=>:modeldocontext"with 2 or more comments"doit"orders them in reverse chronologically"dopost=Post.create!comment1=post.comments.create!(:body=>"first comment")comment2=post.comments.create!(:body=>"second comment")expect(post.reload.comments).toeq([comment2,comment1])endendend
取消 transactions
123456789101112131415161718192021222324
require"rails_helper"RSpec.configuredo|c|c.use_transactional_examples=falsec.order="defined"enddescribeWidget,:type=>:modeldoit"has none to begin with"doexpect(Widget.count).toeq0endit"has one after adding one"doWidget.createexpect(Widget.count).toeq1end# 關閉 transactions,剛剛建立的 Widget 就不會消失it"has one after one was created in a previous example"doexpect(Widget.count).toeq1endafter(:all){Widget.destroy_all}end