CSC/ECE 517 Spring 2023 - E2345. Reimplement QuestionnairesController and QuestionsController
Introduction
This page gives a description of the changes made for the questions_controller.rb, questionnaire_controller.rb, question.rb & questionnaire.rb of Expertiza based OSS project.
Problem Statement
What is needed: This project builds on E2321, and the main goal is to get the endpoints of QuestionsController and QuestionnairesController running in reimplementation-backend repository. Detailed goals of the project are as follows:
- Improving the clarity and conciseness of code: The code should be written in a clean and concise manner. Methods with identical names that perform different functionalities should be renamed for clarity. Functions or functionality that are not clear should be commented on or removed. Any loops or methods that can be refactored for better performance should be addressed.
- Discarding unused functionality: Any unused functionality should be removed from the controllers. This will help to reduce complexity and make the code easier to maintain.
- Reimplement Question and Questionnaire models: Reimplement the two models to facilitate the endpoints of the respective controllers.
- Writing tests for the two models: Tests should be written for both the Questionnaires and the Questions models.
- Writing tests for the two controllers: Tests should be written for both the QuestionnairesController and the QuestionsController. The tests should written in the RSwag test format.
General Design Goals
- Ensure all prior/expected functionality is working correctly, and if not, make any repairs or changes necessary.
- Ensure that the each of the models and controllers have loose coupling and tight cohesion.
- DRY out prior implementation's controller and model methods which have functionality that already exists within the expertiza system.
- Ensure all present test cases still work properly after making the above changes and create additional test cases.
Implementation
The current implementation for the code can be found here E2321.
To get the QuestionnairesController and QuestionsController endpoints running in the reimplementation-back-end repository, we need to reimplement the respective model files and add other dependent files.
The following UML diagram shows the association between models we will be working on -
Below is the implementation plan that we have followed for E2345:
-
Implement basic version of question.rb and questionnaire.rb such that it facilitates the controllers' CRUD operations.
- Add required associations for user.rb, role.rb, question.rb, and questionnaire.rb only.
- The below code snippets represent current implementation of question.rb:
class Question < ApplicationRecord belongs_to :questionnaire # each question belongs to a specific questionnaire validates :seq, presence: true, numericality: true # sequence must be numeric validates :txt, length: { minimum: 0, allow_nil: false, message: "can't be nil" } # user must define text content for a question validates :question_type, presence: true # user must define type for a question validates :break_before, presence: true def as_json(options = {}) super(options.merge({ only: %i[questionnaire_id txt weight seq question_type size alternatives break_before min_label max_label created_at updated_at], include: { questionnaire: { only: %i[name private min_question_score max_question_score instructor_id created_at updated_at questionnaire_type] } } })).tap do |hash| hash['questionnaire'] ||= { id: nil, name: nil } end end end
In the above code, the as_json method is used to decorate the JSON object that is returned as a part of the response body from the controller endpoint. It is used to replace the questionnaire_id with the questionnaire details within the question object in JSON format.
- The below code snippets represent current implementation of questionnaire.rb:
class Questionnaire < ApplicationRecord has_many :questions, dependent: :restrict_with_error belongs_to :instructor before_destroy :check_for_question_associations validate :validate_questionnaire validates :name, presence: true validates :max_question_score, :min_question_score, numericality: true # clones the contents of a questionnaire, including the questions and associated advice def self.copy_questionnaire_details(params) orig_questionnaire = Questionnaire.find(params[:id]) questions = Question.where(questionnaire_id: params[:id]) questionnaire = orig_questionnaire.dup questionnaire.name = 'Copy of ' + orig_questionnaire.name questionnaire.created_at = Time.zone.now questionnaire.updated_at = Time.zone.now questionnaire.save! questions.each do |question| new_question = question.dup new_question.questionnaire_id = questionnaire.id new_question.save! end questionnaire end # validate the entries for this questionnaire def validate_questionnaire errors.add(:max_question_score, 'The maximum question score must be a positive integer.') if max_question_score < 1 errors.add(:min_question_score, 'The minimum question score must be a positive integer.') if min_question_score < 0 errors.add(:min_question_score, 'The minimum question score must be less than the maximum.') if min_question_score >= max_question_score results = Questionnaire.where('id <> ? and name = ? and instructor_id = ?', id, name, instructor_id) errors.add(:name, 'Questionnaire names must be unique.') if results.present? end # Check_for_question_associations checks if questionnaire has associated questions or not def check_for_question_associations if questions.any? raise ActiveRecord::DeleteRestrictionError.new(:base, "Cannot delete record because dependent questions exist") end end def as_json(options = {}) super(options.merge({ only: %i[id name private min_question_score max_question_score created_at updated_at questionnaire_type], include: { instructor: { only: %i[name email fullname password role] } } })).tap do |hash| hash['instructor'] ||= { id: nil, name: nil } end end end
In the above code,
- The as_json method is used to decorate the JSON object that is returned as a part of the response body from the controller endpoint. It is used to replace the instructor_id with the instructor details within the questionnaire object in JSON format.
- The check_for_question_associations method is used to raise an Error if a Questionnaire that has associated questions is tried to be deleted.
- The copy_questionnaire_details method is used to create a new object with the same attributes of the questionnaire and save it to the database. It is called when the copy endpoint is requested.
-
Reimplement questionnaires_controller.rb to incorporate the feedback received in E2321.
- index: This is a GET endpoint that responds with a list of all questionnaires with their attributes.
def index @questionnaires = Questionnaire.order(:id) render json: @questionnaires, status: :ok and return end
- show: This is a GET endpoint that accepts a questionnaire id and responds with the attributes of that questionnaire if it exists, otherwise provides with appropriate error.
def show begin @questionnaire = Questionnaire.find(params[:id]) render json: @questionnaire, status: :ok and return rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found and return end end
- create: This is a POST endpoint that accepts the questionnaire parameters and creates a new questionnaire. Refactor the Create endpoint in questionnaires_controller.rb such that individual fields does not need to be set and validated. The below code represents the revised implementation of the method. A Questionnaire object is created using the new method instead of manual assignment of attributes.
def create begin @questionnaire = Questionnaire.new(questionnaire_params) @questionnaire.display_type = sanitize_display_type(@questionnaire.questionnaire_type) @questionnaire.save! render json: @questionnaire, status: :created and return rescue ActiveRecord::RecordInvalid render json: $ERROR_INFO.to_s, status: :unprocessable_entity end end
- destroy: This is a DELETE endpoint that accepts a questionnaire ID and deletes that questionnaire if it exists, otherwise provides with appropriate error. It should delete the questionnaire only if there are no questions associated to it.
def destroy begin @questionnaire = Questionnaire.find(params[:id]) @questionnaire.delete rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found and return rescue ActiveRecord::RecordInvalid render json: $ERROR_INFO.to_s, status: :unprocessable_entity end end
- update: This is a PUT endpoint that accepts a questionnaire ID and parameters, and, updates that questionnaire with the given parameters if it exists, otherwise provides with appropriate error.
def update # Save questionnaire information begin @questionnaire = Questionnaire.find(params[:id]) @questionnaire.update(questionnaire_params) @questionnaire.save! render json: @questionnaire, status: :ok and return rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found and return rescue ActiveRecord::RecordInvalid render json: $ERROR_INFO.to_s, status: :unprocessable_entity end end
- copy: This is a POST endpoint that accepts a questionnaire ID and creates a new questionnaire (copy) with the same attributes of that questionnaire if it exists, otherwise provides with appropriate error.
def copy begin @questionnaire = Questionnaire.copy_questionnaire_details(params) render json: "Copy of the questionnaire has been created successfully.", status: :ok and return rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found and return rescue ActiveRecord::RecordInvalid render json: $ERROR_INFO.to_s, status: :unprocessable_entity end end
- toggle_access: This is a GET endpoint that changes the access from public to private and vice versa if it exists, otherwise provides with appropriate error.
def toggle_access begin @questionnaire = Questionnaire.find(params[:id]) @questionnaire.private = !@questionnaire.private @questionnaire.save! @access = @questionnaire.private == true ? 'private' : 'public' render json: "The questionnaire \"#{@questionnaire.name}\" has been successfully made #{@access}. ", status: :ok and return rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found and return rescue ActiveRecord::RecordInvalid render json: $ERROR_INFO.to_s, status: :unprocessable_entity end end
-
Reimplement questions_controller.rb to incorporate the feedback received in E2321.
- index: This is a GET endpoint that responds with a list of all questions with their attributes.
def index @questions = Question.order(:id) render json: @questions, status: :ok end
- show: This is a GET endpoint that accepts a question id and responds with the attributes of that question if it exists, otherwise provides with appropriate error.
def show begin @question = Question.find(params[:id]) render json: @question, status: :ok rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found end end
- create: This is a POST endpoint that accepts the question parameters and creates a new question. Refactor the Create endpoint in questions_controller.rb such that individual fields does not need to be set and validated. The below code represents the revised implementation of the method. A Question object is created using the new method instead of manual assignment of attributes.
def create begin questionnaire_id = params[:questionnaire_id] unless params[:questionnaire_id].nil? num_of_existed_questions = Questionnaire.find(questionnaire_id).questions.size question = Question.create( txt: params[:txt], questionnaire_id: questionnaire_id, seq: num_of_existed_questions + 1, question_type: params[:question_type], break_before: true) case question.question_type when 'Scale' question.weight = params[:weight] question.max_label = 'Strongly agree' question.min_label = 'Strongly disagree' when 'Cake', 'Criterion' question.weight = params[:weight] question.max_label = 'Strongly agree' question.min_label = 'Strongly disagree' question.size = '50, 3' when 'Dropdown' question.alternatives = '0|1|2|3|4|5' question.size = nil when 'TextArea' question.size = '60, 5' when 'TextField' question.size = '30' end question.save! render json: question, status: :created rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found and return rescue ActiveRecord::RecordInvalid render json: $ERROR_INFO.to_s, status: :unprocessable_entity end end
- destroy: This is a DELETE endpoint that accepts a question ID and deletes that question if it exists, otherwise provides with appropriate error.
def destroy begin @question = Question.find(params[:id]) @question.destroy rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found and return rescue ActiveRecord::RecordInvalid render json: $ERROR_INFO.to_s, status: :unprocessable_entity end end
- delete_all: This is a DELETE endpoint that takes questionnaire_id as the path parameter and deletes all questions associated to that questionnaire. It returns status 404 if the questionnaire does not exist, status 422 if no questions are associated to that questionnaire and status 200 if all the questions are successfully deleted.
def delete_all begin @questionnaire = Questionnaire.find(params[:id]) if @questionnaire.questions.size > 0 @questionnaire.questions.destroy_all msg = "All questions for Questionnaire ID:" + params[:id].to_s + " has been successfully deleted!" render json: msg, status: :ok else render json: "No questions associated to Questionnaire ID:" + params[:id].to_s, status: :unprocessable_entity and return end rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found and return rescue ActiveRecord::RecordInvalid render json: $ERROR_INFO.to_s, status: :unprocessable_entity end end
- shiw_all: This is a GET endpoint that takes questionnaire_id as the path parameter and shows all questions associated to that questionnaire. It returns status 404 if the questionnaire does not exist, status 422 if no questions are associated to that questionnaire and status 200 if all the questions are successfully displayed.
def show_all begin @questionnaire = Questionnaire.find(params[:id]) @questions = @questionnaire.questions render json: @questions, status: :ok rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found rescue ActiveRecord::RecordInvalid render json: $ERROR_INFO.to_s, status: :unprocessable_entity end end
- update: This is a PUT endpoint that accepts a question ID and parameters, and, updates that question with the given parameters if it exists, otherwise provides with appropriate error.
def update begin @question = Question.find(params[:id]) @question.update(question_params) @question.save! render json: @question, status: :ok and return rescue ActiveRecord::RecordNotFound render json: $ERROR_INFO.to_s, status: :not_found and return rescue ActiveRecord::RecordInvalid render json: $ERROR_INFO.to_s, status: :unprocessable_entity end end
- types: This is a GET endpoint that responds with the list of question types.
def types types = Question.distinct.pluck(:question_type) render json: types.to_a, status: :ok end
-
Write unit tests for Questions model and Questionnaires model using Rspec: Kindly refer to the Testing Methodology section for detailed description.
- Unit tests for Question model: question_spec.rb
- Unit tests for Questionnaire model: questionnaire_spec.rb
-
Write Rspec tests using Swagger API for each endpoint of QuestionsController and QuestionnairesController. Kindly refer to the Testing Methodology section for detailed description.
- Swagger tests for QuestionsController: questions_spec.rb
- Swagger tests for QuestionnairesController: questionnaires_spec.rb
Testing Methodology
Rspec test skeleton for QuestionnairesController and QuestionsController had been added in the previous project E2321 but had not been executed due to missing dependencies. This project focuses on implementing them and getting automated test cases running as expected. In our previous project we implemented the CRUD endpoints but since all the models were not present in reimplementation backend repository, we could only do manual testing of our controller endpoints using Postman. In this project, we focus to create the models required to implement CRUD operations in the reimplementation-back-end repository and test the endpoints using Swagger API.
Controller Tests
To run the controller tests:
- git clone
- cd reimplementation-back-end/
- bundle install
- rspec spec/requests/api/v1/questionnaires_controller_spec.rb
- rspec spec/requests/api/v1/questions_controller_spec.rb
- RAILS_ENV=test rails rswag
Tests for QuestionnairesController: questionnaires_spec.rb
Sr No | Test Description |
---|---|
1 | Test to create a new Questionnaire with valid parameters. |
2 | Test to create a new Questionnaire with invalid parameters. |
3 | Test to create a copy of Questionnaire with existing id in database. |
4 | Test to create a copy of Questionnaire with non-existing id in database. |
5 | Test to list the Questionnaires. |
6 | Test to update a Questionnaire (using put request) with correct parameters. |
7 | Test to update a Questionnaire (using put request) with incorrect parameters. |
8 | Test to update a Questionnaire (using put request) with non-existing id in database. |
9 | Test to delete Questionnaire with existing id in database. |
10 | Test to delete Questionnaire with the non-existing id in database. |
11 | Test to show a Questionnaire with a existing id in database. |
12 | Test to show a Questionnaire with non-existing id in database. |
13 | Test to toggle private boolean flag of a Questionnaire with a existing id in database. |
14 | Test to toggle private boolean flag of a Questionnaire with non-existing id in database. |
15 | Test to update the Questionnaire (using patch request) with correct parameters. |
16 | Test to update the Questionnaire (using patch request) with incorrect parameters. |
17 | Test to update the Questionnaire (using patch request) with non-existing id in the database. |
Tests for QuestionsController: questions_spec.rb
Sr No | Test Description |
---|---|
1 | Test to create a new Question with valid parameters. |
2 | Test to create a new Question with invalid parameters. |
3 | Test to create a new Question with non-existing Questionnaire id in the database |
4 | Test to list the Questions in the database. |
5 | Test to update the Question (using put request)with correct parameters. |
6 | Test to update the Question (using put request) with incorrect parameters. |
7 | Test to update the Question (using put request)with non-existing id in the database. |
8 | Test to delete Question with existing id in the database. |
9 | Test to delete Question with the non-existing id in the database. |
10 | Test to show a Question with existing id in the database. |
11 | Test to show a Question with non-existing id in the database. |
12 | Test to get a types of Questions present in the database. |
13 | Test to delete all Questions of a Questionnaire with a valid Questionnaire id. |
14 | Test to delete all Questions of a Questionnaire with an invalid Questionnaire id. |
15 | Test to update the Question (using patch request) with correct parameters. |
16 | Test to update the Question (using patch request) with incorrect parameters. |
17 | Test to update the Question (using patch request) with non-existing id in the database. |
18 | Test to show all Questions of a Questionnaire with a valid Questionnaire id. |
19 | Test to show all Questions of a Questionnaire with an invalid Questionnaire id. |
Model Tests
To run the model tests:
- git clone
- cd reimplementation-back-end/
- bundle install
- rspec spec/models/questionnaire_spec.rb
- rspec spec/models/question_spec.rb
Tests for Questionnaire model: questionnaire_spec.rb
Sr No | Test Description |
---|---|
1 | Test that Questionnaire requires a name. |
2 | Test validates the name of the questionnaire. |
3 | Test validates the instructor id in the questionnaire . |
4 | Test validates the maximum score in the questionnaire. |
5 | Test ensures maximum score of the questionnaire is an integer. |
6 | Test ensures maximum score is positive. |
7 | Test ensures maximum score is greater than the minimum score. |
8 | Test validates minimum score of a questionnaire. |
9 | Test ensures minimum score is smaller than maximum score. |
10 | Test ensures minimum score is an integer. |
11 | Test validates the association that a questionnaire comprises of several questions. |
12 | Test ensures that a questionnaire is not deleted when it has questions associated. |
13 | Test ensures calls from the method copy_questionnaire_details. |
14 | Test ensures creation of a copy of given questionnaire. |
15 | Test ensures creation of copy of all the present questionnaire in the database. |
Tests for Question model: question_spec.rb
Sr No | Test Description |
---|---|
1 | Test that Question has valid attributes defined. |
2 | Test ensures that a question is not valid without seq field. |
3 | Test that Question sequence number must be numerical. |
4 | Test ensures that a question is not valid without txt field. |
5 | Test ensures that a question is not valid without question_type field. |
6 | Test ensures that a question is not valid without break_before field. |
7 | Test ensures that a question does not exist without a questionnaire. |
8 | Test ensures that a question object is deleted properly taking all its association into consideration. |
Future Work
- The questions and questionnaires model in the reimplementation-back-end repo has been updated to have question_type and questionnaire_type attribute instead of type attribute. Ruby has implicit inheritance when the type attribute is used. However, our repo does not have the dependent models for each type of Question and Questionnaire. For future implementation, those model classes could be added and this attribute can be refactored in the model and controller files.
- Implement other associations (for example: assignments) within each models.
Relevant Links
- Github Repository: https://github.com/Vineet2311/reimplementation-back-end
- Pull Request: https://github.com/expertiza/reimplementation-back-end/pull/20
- VCL Server: http://152.7.178.189:8080
- Test Video Link: https://youtu.be/zkId16tklXI
Contributors
This feature was created as part of Dr. Edward Gehringer's "CSC/ECE 517: Object-Oriented Design and Development" class, Spring 2023. The contributors were: Vineet Vimal Chheda, Rohan Jigarbhai Shah, and Aditya Srivastava. Our project mentor was Ankur Mundra (amundra@ncsu.edu)