modelテストの準備#
今回はPostモデルにタイトルカラムがあるかどうかと文字数のテストをする。
app/models/post.rb
class Post < AplicationRecord
belongs_to :user
validates :title, presence: true, length: {maximum: 20}
end
ファイルの作成#
①spec配下にmodelsフォルダとfactoriesフォルダを作成し、テストしたいモデルのファイルを作成する。今回は spec/models/post_spec.rbを作成
②FactroyBotを使用可能にする。
使用すると user = create(:user)のようにDB登録やモデルのビルドができるようになる。
spec配下にsupportフォルダとfactory_bot.rbファイルを作成し、下記を記述。
ユーザーがログインしている状態でないと投稿出来ないことをテストするためpost_spec.rb user_spec.rbの2ファイルを作成する。
spec/support/factroy_bot.rb
RSpec.configure do |config|
config.include FactroyBot::Syntax::Methods
end
③spec/rails_helper.rbの編集
spec/rails_helper.rb
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'support/factory_bot'
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
#今回の記事では関係ないがsystem_specにおいてヘッドレスモードでchromeを起動するための記述
config.before(:each) do |example|
if example.metadata[:type] == :system
if example.metadata[:js]
driven_by :selenium_chrome_headless, screen_size: [1400, 1400]
else
driven_by :rack_test
end
end
end
#capybaraに関する記述
config.include Capybara::DSL
end
ダミーデータの作成#
spec/factories/user.rb
FactoryBot.define do
factory :user do
name {Faker::Name.name}
email {Faker::Internet.email}
password {'password'}
password_confirmation {'password'}
end
end
spec/factories/post.rb
FactoryBot.define do
factory :post do
body {Faker::Lorem.characters(number: 20)}
user
end
end
テストコードの作成#
spec/models/post_spec.rb
require 'rails_helper'
RSpec.describe 'post model test', type: :model do
describe 'validation test' do
#factoriesで作成したダミーデータを使用する
let(:user) {FactoryBot.create(:user)}
let!(:post) {build(:post, user_id: user.id)}
#test_postを作成し、空欄での登録ができるか確認
subject {test_post.valid?}
let(:test_post) {post}
it 'titleカラムが空欄でないこと' do
test_post.title = ''
is_expected.to eq false;
end
it '21文字以上であればfalse' do
post.title = Faker::Lorem.characters(number: 21)
expect(post).to eq false;
end
end
end
RSpecの実行#
$ bin/rspec spec/models/post_spec.rb