Commit 74ee7265 by Akash kumar

Added department module with test cases

parent ebb60b88
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
// Place all the styles related to the department controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
class Api::V1::DepartmentsController < ApplicationController
def index
department = Department.all.order(created_at: :desc)
render json: department
end
def create
department = Department.create!(department_params)
if department
render json: department
else
render json: department.errors
end
end
def show
if department
render json: department
else
render json: department.errors
end
end
def destroy
department&.destroy
render json: { message: 'Department deleted!' }
end
private
def department_params
params.permit(:departmentName, :description)
end
def department
@department ||= Department.find(params[:id])
end
end
\ No newline at end of file
...@@ -5,6 +5,7 @@ class Api::V1::RecipesController < ApplicationController ...@@ -5,6 +5,7 @@ class Api::V1::RecipesController < ApplicationController
end end
def create def create
puts "valuerecipe_params #{recipe_params}"
recipe = Recipe.create!(recipe_params) recipe = Recipe.create!(recipe_params)
if recipe if recipe
render json: recipe render json: recipe
......
module DepartmentHelper
end
import React from "react";
import { Link } from "react-router-dom";
export default () => (
<div className="vw-100 vh-100 primary-color d-flex align-items-center justify-content-center">
<div className="jumbotron jumbotron-fluid bg-transparent">
<div className="container secondary-color">
<h1 className="display-4">Department</h1>
<p className="lead">
You can add department here
</p>
<hr className="my-4" />
<Link
to="/add"
className="btn btn-lg custom-button"
role="button"
>
Create Department
</Link>
</div>
</div>
</div>
);
\ No newline at end of file
...@@ -27,6 +27,14 @@ export default () => ( ...@@ -27,6 +27,14 @@ export default () => (
> >
View Employees View Employees
</Link> </Link>
<br></br>
<Link
to="/department"
className="btn btn-lg custom-button"
role="button"
>
Go to department page
</Link>
</div> </div>
</div> </div>
</div> </div>
......
import React from "react";
import { Link } from "react-router-dom";
class NewDepartment extends React.Component {
constructor(props) {
super(props);
this.state = {
departmentName: "",
description: "",
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
onSubmit(event) {
event.preventDefault();
const url = "/api/v1/departments/create";
const { departmentName, description} = this.state;
if (departmentName.length == 0 || description.length == 0 )
return;
const body = {
departmentName,
description
};
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch(url, {
method: "POST",
headers: {
"X-CSRF-Token": token,
"Content-Type": "application/json"
},
body: JSON.stringify(body)
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(response => this.props.history.push(`/view/${response.id}`))
.catch(error => console.log(error.message));
}
render() {
return (
<div className="container mt-5">
<div className="row">
<div className="col-sm-12 col-lg-6 offset-lg-3">
<h1 className="font-weight-normal mb-5">
Add a new department
</h1>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label htmlFor="recipeName">Department name</label>
<input
type="text"
name="departmentName"
id="departmentName"
className="form-control"
required
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="recipeIngredients">Description</label>
<input
type="text"
name="description"
id="description"
className="form-control"
required
onChange={this.onChange}
/>
</div>
<button type="submit" className="btn custom-button mt-3">
Create Department
</button>
<Link to="/department" className="btn btn-link mt-3">
Back to Department
</Link>
</form>
</div>
</div>
</div>
);
}
}
export default NewDepartment;
\ No newline at end of file
import React from "react";
import { Link } from "react-router-dom";
class ViewDepartment extends React.Component {
constructor(props) {
super(props);
this.state = { department: { departmentName: "",description:"" } };
this.deleteDepartment = this.deleteDepartment.bind(this);
}
componentDidMount() {
const {
match: {
params: { id }
}
} = this.props;
const url = `/api/v1/department/show/${id}`;
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(response => this.setState({ department: response }))
.catch(() => this.props.history.push("/department"));
}
render() {
const { department } = this.state;
return (
<div className="">
<div className="hero position-relative d-flex align-items-center justify-content-center">
<div className="overlay bg-dark position-absolute" />
<h1 className="display-4 position-relative text-white">
{department.departmentName}
</h1>
</div>
<div className="container py-5">
<div className="row">
<div className="col-sm-12 col-lg-7">
<h5 className="mb-2"> {department.description}</h5>
</div>
<div className="col-sm-12 col-lg-2">
<button type="button" className="btn btn-danger" onClick={this.deleteDepartment}>
Delete department
</button>
</div>
</div>
<Link to="/department" className="btn btn-link">
Back to department
</Link>
</div>
</div>
);
}
deleteDepartment() {
const {
match: {
params: { id }
}
} = this.props;
const url = `/api/v1/department/destroy/${id}`;
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch(url, {
method: "DELETE",
headers: {
"X-CSRF-Token": token,
"Content-Type": "application/json"
}
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(() => this.props.history.push("/department"))
.catch(error => console.log(error.message));
}
}
export default ViewDepartment;
\ No newline at end of file
...@@ -7,6 +7,9 @@ import NewRecipe from "../components/NewRecipe"; ...@@ -7,6 +7,9 @@ import NewRecipe from "../components/NewRecipe";
import Employees from "../components/Employees"; import Employees from "../components/Employees";
import Employee from "../components/Employee"; import Employee from "../components/Employee";
import NewEmployee from "../components/NewEmployee"; import NewEmployee from "../components/NewEmployee";
import Department from "../components/Department";
import NewDepartment from "../components/NewDepartment";
import ViewDepartment from "../components/ViewDepartMent";
export default ( export default (
<Router> <Router>
...@@ -18,6 +21,9 @@ export default ( ...@@ -18,6 +21,9 @@ export default (
<Route path="/employees" exact component={Employees} /> <Route path="/employees" exact component={Employees} />
<Route path="/employee/:id" exact component={Employee} /> <Route path="/employee/:id" exact component={Employee} />
<Route path="/employee" exact component={NewEmployee} /> <Route path="/employee" exact component={NewEmployee} />
<Route path="/department" exact component={Department} />
<Route path="/add" exact component={NewDepartment} />
<Route path="/view/:id" exact component={ViewDepartment} />
</Switch> </Switch>
</Router> </Router>
); );
\ No newline at end of file
class Department < ApplicationRecord
validates :departmentName, presence: true
validates :description, presence: true
end
...@@ -17,6 +17,14 @@ Rails.application.routes.draw do ...@@ -17,6 +17,14 @@ Rails.application.routes.draw do
post 'recipes/uploadFile' post 'recipes/uploadFile'
end end
end end
namespace :api do
namespace :v1 do
get 'departments/index'
post 'departments/create'
get 'department/show/:id', to: 'departments#show'
delete 'department/destroy/:id', to: 'departments#destroy'
end
end
root 'homepage#index' root 'homepage#index'
get '/*path' => 'homepage#index' get '/*path' => 'homepage#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
......
class CreateDepartments < ActiveRecord::Migration[5.2]
def change
create_table :departments do |t|
t.string :departmentName, null: false
t.string :description, null: false
t.timestamps
end
end
end
...@@ -10,11 +10,18 @@ ...@@ -10,11 +10,18 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_09_30_024252) do ActiveRecord::Schema.define(version: 2020_10_02_122459) do
# These are extensions that must be enabled in order to support this database # These are extensions that must be enabled in order to support this database
enable_extension "plpgsql" enable_extension "plpgsql"
create_table "departments", force: :cascade do |t|
t.string "departmentName", null: false
t.string "description", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "employees", force: :cascade do |t| create_table "employees", force: :cascade do |t|
t.string "firstName", null: false t.string "firstName", null: false
t.string "lastName", null: false t.string "lastName", null: false
......
FactoryBot.define do
factory :department do
departmentName { 'Quality' }
description {'Tests quality of product at different stages'}
end
factory :random_department, class: Department do
departmentName { Faker::Name.name }
description { Faker::Food.description }
end
end
\ No newline at end of file
require 'rails_helper'
RSpec.describe Department, type: :model do
context 'Validation Test Case' do
let(:department) { build(:random_department) }
it 'departmentName validation' do
#department = Department.new(departmentName: 'Quality', description: 'Tests quality of product at different stages')
department.departmentName = nil
expect(department.save).to eq(false)
end
it 'description validation' do
#department = Department.new(departmentName: 'Quality', description: 'Tests quality of product at different stages')
department.description = nil;
expect(department.save).to eq(false)
end
it 'null validation' do
department = Department.new(departmentName: 'Quality', description: 'Tests quality of product at different stages').save
expect(department).to eq(true)
end
end
context 'Department Table Operations Test Case' do
it 'Save Data Test' do
department = Department.new(departmentName: 'Quality', description: 'Tests quality of product at different stages').save
expect(department).to eq(true)
end
end
#pending "add some examples to (or delete) #{__FILE__}"
end
require 'rails_helper'
RSpec.describe "Api::V1::Departments", type: :request do
describe "GET /index" do
it "returns http success" do
get("/api/v1/departments/index")
expect(response.status).to eq(200)
end
end
describe "POST /create" do
it "returns http success" do
get "/api/v1/departments/create"
expect(response).to have_http_status(:success)
end
end
describe "GET /show" do
it "returns http success" do
get "/api/v1/departments/show/:1"
expect(response).to have_http_status(:success)
end
end
describe "DELETE /destroy" do
it "returns http success" do
get "/api/v1/departments/destroy"
expect(response.status).to eq(200)
end
end
end
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment