RSpec-Rails (基礎篇)(2): 安裝RSpec至Rails
產生新專案
$ rails new demo-app
Gemfile
group :development, :test do
gem 'rspec-rails'
end
$ bundle install
$ rails generate rspec:install
$ rails generate scaffold post
$ rake db:migrate
$ rspec
測試當中會有許多不必要的測試檔案,因此從頭來產生一次。
$ rails destroy scaffold post
將RSpec相關的產生器關掉。
/config/application.rb
config.generators do |g|
g.controller_specs false
g.view_specs false
g.helper_specs false
g.routing_specs false
g.request_specs false
end
再產生一次scaffold
$ rails generate scaffold post title:string content:text
$ rake db:drop db:create db:migrate
$ rspec
會只剩下model測試
/spec/models/post_spec.rb
require 'rails_helper'
RSpec.describe Post, type: :model do
it "is accessible" do
post = Post.create!
expect(post).to eq(Post.last)
end
it "has title and content columns" do
columns = Post.column_names
expect(columns).to include("id")
expect(columns).to include("title")
expect(columns).to include("content")
expect(columns).not_to include("user_id")
end
end