[英]Testing model saving using devise
我有一個表格,一次最多可以接受20個問題。 它接收一個數組並將問題保存到數據庫中。 每個問題有4個答案。 我可以將問題保存到數據庫中。 但是,我遇到了將它們鏈接到用戶的問題。
這是控制器:
class QuestionsController < ApplicationController
def new
@question_group = []
20.times do
@question_group << Question.new
end
end
def create
params["questions"].each do |question|
# If the question is empty, we don't want to save it
if !question_empty?(question)
current_user.questions.create!(question_params(question))
end
end
flash[:success] = "Quiz made!"
redirect_to root_url
end
它無法通過以下測試:
require 'test_helper'
class CreateQuestionsTest < ActionDispatch::IntegrationTest
def setup
@user = users(:cookie)
end
test "should save the right amount of questions" do
post user_session_path, :user => {:email => @user.email, :password => @user.password}
get new_question_path
assert_difference 'Question.count', 1 do
post questions_path, {"questions" => [{"question" => "What is 1+1?",
"a1" => "0", "a2" => "1", "a3" => "2", "a4" => "3"}]}
end
assert_difference 'Question.count', 2 do
post questions_path, { "questions" => [{"question" => "What is 1+1?",
"a1" => "0", "a2" => "1", "a3" => "2", "a4" => "3"},
{"question" => "What is 1 - 1?", "a1" => "1",
"a2" => "0", "a3" => "2", "a4" => "3"}]}
end
end
end
在上面的測試中,問題未保存。 這適用於手動測試,但是我無法為此建立自動測試。
我建議您對模型設計進行一些更改。 而不是處理數組。 我將創建一個像QuestionForm
這樣的父對象來接受嵌套表單:
class QuestionForm < ActiveRecord::Base
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions, reject_if: proc { |attributes|
#your reject validations here
}, allow_destroy: true
end
然后在您的Question
模型中:
class Question < ActiveRecord::Base
belongs_to :question_form
end
然后您測試QuestionForm
流(帶有嵌套問題)
抱歉,它沒有回答您的問題,只是一個提示;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.