Rspecの導入
新規アプリ作成
$ rails _5.2.3_ new sample-app -d postgresql --skip-bundle && cd sample-app
不要なファイルが生成されないように設定
config/application.rb
module SampleApp
class Application < Rails::Application
# ここから下を追加(scaffold対策)
config.generators do |g|
g.javascripts false
g.helper false
g.test_framework false
g.test_framework :rspec,
fixtures: true,
view_specs: false,
helper_specs: false,
routing_specs: false,
controller_specs: false,
request_specs: false
g.fixture_replacement :factory_bot, dir: "spec/factories"
end
end
end
Rspecで必要なGemの追加
Gemfile
group :development, :test do
# 追加
gem 'rspec-rails'
gem 'factory_bot_rails'
end
group :test do
# 追加
gem 'capybara'
gem 'selenium-webdriver'
end
bundleから諸々のフォルダ作成、SystemrSpecとFactoryBotの導入
bundle install、scaffold、db:migrate、rspec generate、factorybot generate、systemフォルダ作成、post_spec.rbファイル作成を一発で!
$ bundle install --path vendor/bundle && rails db:create && rails g scaffold post title:string detaile:string && rails db:migrate && rails g rspec:install && mkdir spec/system && touch spec/system/post_spec.rb
chromedriverを入れてない方はこちら
$ brew install chromedriver && brew upgrade chromedriver
task_spec.rb例文)
spec/system/post_spec.rb
require 'rails_helper'
RSpec.describe 'MyString', type: :system do
before do
FactoryBot.create(:post)
@posts = Post.all.order(created_at: :desc)
end
describe 'xxxxxxxxxx' do
context 'xxxxxxxxxx' do
FactoryBot.create(:post)
it 'xxxxxxxxxx' do
visit posts_path
expect(page).to have_content 'MyString'
end
end
end
end
factories例文)
spec/factories/posts.rb
FactoryBot.define do
factory :post do
title { "MyString" }
detaile { "MyString" }
end
end
rspecテストを実行
$ bundle exec rspec ./spec/system/post_spec.rb
参考にした記事
https://qiita.com/jnchito/items/c7e6e7abf83598a6516d
https://qiita.com/naoki_mochizuki/items/1d3026a32786642fc762