2
5

More than 3 years have passed since last update.

【RSpec・Modelsテスト】画像を複数投稿するカラムを持つモデルでのテストデータの作り方・テストの通し方

Last updated at Posted at 2020-04-15

環境

carrierwave
rails 6.2.0
capybara 3.28.0
rspec-rails
rails-controller-testing 1.0.4
factory_bot_rails

前提

  • @postというモデルがある。
  • @postモデルは@userが投稿する。
  • @postモデルは次のカラムを持つ。
  型    カラム名
string name
text content
string picture
string user_id
  • pictureカラムには画像が複数はいる。(つまり複数投稿できる。)

  • FactoryBotと書くのを省略するため、以下を記述します。

spec/rails_helper.rb
~~省略~~
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods  #記述する
end
~~省略~~

postモデルのバリデーション

postモデルのバリデーションは以下の通りです。

app/model/post.rb
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

今回通したいテスト

今回通したいテストはこちらです。

spec/models/post.spec.rb
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を使ってテストデータを作成する

spec/factories/posts.rb
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

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5