之前很為寫(xiě)測(cè)試頭痛砸捏,從現(xiàn)在開(kāi)始測(cè)試也要認(rèn)真寫(xiě)啊 ?? 裁赠。
總是搞不懂 describe
context
it
let
subject
before/after
之間先后順序以及含義焚挠。大概看了一下 rspec-style-guide
康二,可以有一定的了解嫡纠。本文摘自 The RSpec Style Guide,詳盡的請(qǐng)參考原文丸冕。
完整結(jié)構(gòu):
class
class Article
def summary
#...
end
def self.latest
#...
end
end
article_spec.rb
describe Article do
subject { FactoryGirl.create(:some_article) }
let(:user) { FactoryGirl.create(:user) }
before do
# ...
end
after do
# ...
end
describe '#summary' do
context 'when there is a summary' do
it 'returns the summary' do
# ...
end
end
end
describe '.latest' do
context 'when latest' do
it 'returns the latest data' do
# ...
end
end
end
end
articles_controller_spec.rb
# A classic example for use of contexts in a controller spec is creation or update when the object saves successfully or not.
describe ArticlesController do
let(:article) { double(Article) }
describe 'POST create' do
before { allow(Article).to receive(:new).and_return(article) }
it 'creates a new article with the given attributes' do
expect(Article).to receive(:new).with(title: 'The New Article Title').and_return(article)
post :create, article: { title: 'The New Article Title' }
end
it 'saves the article' do
expect(article).to receive(:save)
post :create
end
context 'when the article saves successfully' do
before do
allow(article).to receive(:save).and_return(true)
end
it 'sets a flash[:notice] message' do
post :create
expect(flash[:notice]).to eq('The article was saved successfully.')
end
it 'redirects to the Articles index' do
post :create
expect(response).to redirect_to(action: 'index')
end
end
context 'when the article fails to save' do
before do
allow(article).to receive(:save).and_return(false)
end
it 'assigns @article' do
post :create
expect(assigns[:article]).to eq(article)
end
it 're-renders the 'new' template' do
post :create
expect(response).to render_template('new')
end
end
end
end