環境
carrierwave
rails 6.2.0
capybara 3.28.0
rspec-rails
rails-controller-testing 1.0.4
factory_bot_rails
前提
型 | カラム名 |
---|---|
string | name |
text | content |
string | picture |
string | user_id |
pictureカラムには画像が複数はいる。(つまり複数投稿できる。)
FactoryBotと書くのを省略するため、以下を記述します。
~~省略~~
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods #記述する
end
~~省略~~
postモデルのバリデーション
postモデルのバリデーションは以下の通りです。
class Post < ApplicationRecord
belongs_to :user
has_many :pictures, dependent: :destroy
mount_uploaders :picture, PictureUploader
serialize :picture, JSON #pictureはjson型です
validates :user_id, presence: true
validates :content, presence: true
validates :name, presence: true
validates :picture, presence: true
end
今回通したいテスト
今回通したいテストはこちらです。
require 'rails_helper'
RSpec.describe Post, type: :model do
it "name、content、picture、user_idがある場合有効である" do
post = create(:post)
expect(post).to be_valid
end
end
factoryを使ってテストデータを作成する
FactoryBot.define do
factory :post do
user_id {"1"}
name { "test" }
content { "tester" }
picture { [ Rack::Test::UploadedFile.new(Rails.root.join( 'app/assets/images/test.png'), 'app/assets/images/test.png') ]} #画像はjson型なので[]で画像データを囲む必要がある。
association :user #@postモデルは@userが投稿するので、関連付けを定義する。
end
end
※テストデータのカラムは必ず { } で括ってください
詳細説明
画像を投稿する様のテストデータを作成
app/assets/imagesにテストデータとしてtest.pngを配置します。
Rack::Test::UploadedFile.new(Rails.root.join()オブジェクト
Rack::Test::UploadedFileを指定すればRailsでは画像として認識してくれます。
Rack::Test::UploadedFileの引数として画像のパスをRails.root.joinで指定します。
投稿する画像がjson型の場合は[]で画像データを囲む
投稿される画像の型はjson型なので画像データを[]で囲む必要があります。
[]がない状態でテストをするとpath name contains null byte
と表示されテストが通りません。
アソシエーションの定義
@postは@userが投稿するので、ファクトリ内でassociation :user
を定義する必要があります。
参考URL
https://qiita.com/tanegashiman/items/9dcd872e3d84dca2d57c