LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】複数レコード一括保存のRspecの書き方

Posted at

https://ryucoding.com/programming/rails-form-bulk-create
で紹介されている複数レコードを一括保存するcreateアクションをテストするリクエストspecの書き方で詰まったのでその備忘録です。

テスト対象のコントローラーとアクション

 //questions_controller
def create
    @form = Form::QuestionCollection.new(question_collection_params)
    if @form.save
      redirect_to root_url
    else
      render 'new'
    end
  end
.
.
.
.
.

 def question_collection_params
    params.require(:form_question_collection).permit(questions_attributes: [:content, :mode_num])
 end

クイズ出題アプリで[question]という出題文を表すモデルを同時に10個作成するためのアクションです。

rspec

 //questions_request_spec.rb

 describe "POST /create" do
      context "空欄なく入力した場合" do
        it "redirects to root path" do
          expect{
          post questions_path, params: {form_question_collection:
                                      {questions_attributes:
                                       {0=> {content: "test question1", mode_num:1},
                                        1 =>{content: "test question2", mode_num:1},
                                        2 =>{content: "test question3", mode_num:1},
                                        3 =>{content: "test question4", mode_num:1},
                                        4 =>{content: "test question5", mode_num:1},
                                        5 =>{content: "test question6", mode_num:1},
                                        6 =>{content: "test question7", mode_num:1},
                                        7 =>{content: "test question8", mode_num:1},
                                        8 =>{content: "test question9", mode_num:1},
                                        9 =>{content: "test question10", mode_num:1}}}}
           }.to change(Question, :count).by (10)
          expect(response).to redirect_to root_path
        end
      end

[content]と[mode_num]はカラム名です。保存に成功し際はroot_pathにリダイレクトすることをテストするためのコードです。
上記の書き方で同時に10個のレコードをcreateするアクションのリクエストspecを実現できました。

0
0
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
0
0