コントローラのテストコードを書けるようになる
RailsのController Spec | 酒と涙とRubyとRailsと
Ruby on Rails、RSpecを使ってコントローラのテストを書いてみる - naichi's lab
RailsでController Specを書く際に知っておきたいTips
Gemfile
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
gem 'pry-byebug'
gem "letter_opener", "~> 1.1.0"
gem 'rspec-rails', '~> 3.5'
gem 'rails-controller-testing'
gem "factory_girl_rails"
end
GET #index
◯describe/context/itの使い分け
①describe : テスト対象が何か
②context : 条件は何か (with or whenから始める)
③it : アウトプットは何か
spec/controllers/blogs_controller_spec.rb
POST #create
Rails5でコントローラのテストをController specからRequest specに移行する
Gemfile
テスト用データ作成
spec/factories/blogs.rb
FactoryGirl.define do
factory :blog do
title "title"
end
end
blogs_controller_spec.rb
describe 'POST #create' do
let(:blog_attributes) { attributes_for(:blog) }
it "新規作成後に@blogのshowに遷移すること" do
post :create, params: { blog: blog_attributes }, session: {}
blog = Blog.last
response.should redirect_to blog_path(blog)
end
it "新規作成後に@blogのshowに遷移すること" do
expect{
post :create, params: { blog: blog_attributes }, session: {}
}.to change(Blog, :count).by(1)
end