【问题标题】:Testing model saving using devise使用设计测试模型保存
【发布时间】:2016-09-04 07:57:22
【问题描述】:

我有一个表格,一次最多可以接受 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

在上面的测试中,问题没有被保存。这适用于手动测试,但我无法为其构建自动化测试。

【问题讨论】:

    标签: html ruby-on-rails model-view-controller


    【解决方案1】:

    我建议您对模型设计进行一些更改。而不是处理数组。我会创建一个父对象,如 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 流程(带有嵌套问题)

    抱歉,它没有回答您的问题,只是一个提示;)

    【讨论】:

    • 是的,我一开始也想过这个问题,但是如果希望能够创建一个可以放在不同组中的问题池。我不确定嵌套属性是否可以帮助我。我将不得不阅读它。谢谢!
    猜你喜欢
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2012-03-15
    • 2016-11-25
    相关资源
    最近更新 更多