前提・実現したいこと
RSpec 実行時に予めデータが入っていて欲しい。
発生している問題
マイグレーション時にデータを投入しています。
RAILS_ENV=test bin/rails db:create db:migrate
するとデータは入っているのですが、RSpec を動かすと消えてしまいます。
RSpec の設定とかでどうにかなるのでしょうか?
該当のソースコード
ruby
1# マイグレーションファイル 2class CreateRegions < ActiveRecord::Migration[6.0] 3 def self.up 4 create_table :regions do |t| 5 t.string :name 6 end 7 8 %w[ 9 北海道 10 東北地方 11 関東地方 12 中部地方 13 関西地方 14 中国地方 15 四国地方 16 九州地方 17 ].each do |name| 18 Region.create(name: name) 19 end 20 end 21 22 def self.down 23 drop_table :regions 24 end 25end
ruby
1# spec/models/region_spec.rb 2require 'rails_helper' 3 4RSpec.describe Region, type: :model do 5 it { expect(Region.count).to eq 8 } 6end
試したこと
shell
1$ RAILS_ENV=test bin/rails db:drop db:create db:migrate 2 3$ bin/rails runner -e test 'p Region.count' 48 5 6$ bundle exec rspec spec/models/region_spec.rb 7F 8 9Failures: 10 11 1) Region is expected to eq 8 12 Failure/Error: it { expect(Region.count).to eq 8 } 13 14 expected: 8 15 got: 0 16 17 (compared using ==) 18 # ./spec/models/region_spec.rb:4:in `block (2 levels) in <top (required)>' 19 20Finished in 0.04443 seconds (files took 5.4 seconds to load) 211 example, 1 failure 22 23Failed examples: 24 25rspec ./spec/models/region_spec.rb:4 # Region is expected to eq 8
補足情報(FW/ツールのバージョンなど)
以下の方法はなるべくやりたくないです。
(マイグレーション時にデータ投入したい。データ投入ロジックは DRY にしたい)
- seeds.rb などを使う
- fixtures を使う
あなたの回答
tips
プレビュー