测试多个的Rails属于使用夹具的模型

时间:2014-12-13 08:27:29

标签: ruby-on-rails

我有三个型号。 QuestionAnswerReceivedAnswer

问题包含问题。 答案包含该特定问题的有效答案 收到的答复包含参与者提供的答案。它必须是有效答案之一,它还包含一些与参与者相关的数据

以下是关系:

问题有很多答案并得到答案。 答案属于问题 收到的答案属于问答

received_answer.rb

class ReceivedAnswer < ActiveRecord::Base
  belongs_to :answer
  belongs_to :question

end

我创建了以下灯具

questions.yml

one:
    text: Hello World

answers.yml

answer_one:
  answer_option: A
  answer_text: Football

AnswerTest的设置

    def setup
        @question = questions(:one)
        @answer = @question.answers.build(answer_text: 'Hello World')
    end

完美无缺。

我应该如何设置已接收的答案? 我尝试过以下方法:

 def setup
    @answer = answers(:answer_one)
    @received_answer = @answer.question.received_answers.build(phone_number: 'phone 1')
  end

我有以下问题:

  • 架构是否正确?
  • 应该使用哪种型号以及如何构建收到的答案?

1 个答案:

答案 0 :(得分:1)

让我们从一个真实的例子开始吧。

首先,问题和所需的答案选项:

问题:您对Rails有多少年的经验?

答案选项

  • 没有任何经验
  • &LT; 1年
  • 1 - 3年
  • 3 - 5年
  • &GT; 5年

一些回复:

号码|名字|经验

  1. |经验丰富的编码器| &GT; 5年
  2. | First Coder | 1 - 3年
  3. |第二编码器| 1 - 3年
  4. |新手编码器| &LT; 1年
  5. | Java编码器|没有任何经验
  6. ...

    所以每个问题都有一些答案选择和一些答案。

    class Question < ActiveRecord::Base
      has_many :answer_choices
      has_many :responses
    end
    

    每个答案选择都属于一个问题。

    class AnswerChoice < ActiveRecord::Base
      belongs_to :question
    end
    

    每个回复都属于一个问题和一个用户。

    class Response < ActiveRecord::Base
      belongs_to :question
      belongs_to :user
    end
    

    answer_choiceresponse之间没有belongs_to关系。然而,存在一个限制,即问题的答复中的值仅限于相关的答案选择。这不是在模型级别处理的限制,而是在视图级别,当某人正在回答问题时,正在为问题显示可能的答案选项。

    灯具:

    # questions.yml
    one:
      text: Hello World
    
    # answer_choices.yml
    one:
      question: one # This would associate answer_choice_one to questions(:one)
      answer_option: A
      answer_text: Football
    two:
      question: one # This would associate answer_choice_one to questions(:one)
      answer_option: B
      answer_text: Soccer
    
    # responses.yml
    one:
      user: one  # This would associate response_one to users(:one)
      question: one # This would associate response_one to questions(:one)
      answer_text: Football # There is no association here, but picking a value in the answer_choices fixture.
    
    # users.yml
    one:
      name: First Person
    

    测试设置:

    def setup
       @question = questions(:one)
       @answer_choice_one = answer_choices(:one)
       @answer_choice_two = answer_choices(:two)
    
       @user = users(:one)
       @first_response = responses(:one)
    end
    
    test '.... ' do
      assert_equal @first_response.answer_text, @answer_choice_one.answer_text
    end
    

    在另一个注释中,多个belongs_to关系是有效的,并且可以使用与上面相同的方式使用fixtures进行测试,其中answer_choice / response与问题相关。请查看有关在导轨指南的The Low-down on Fixtures部分中使用关联的详细信息。