Skip to content

Commit

Permalink
Test(contract): Add 'dependent: destroy' to contract -> time_sheet re…
Browse files Browse the repository at this point in the history
…lation.

Add tests.
  • Loading branch information
chrisma committed Nov 18, 2016
1 parent 80cf86a commit 54a52c9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
3 changes: 2 additions & 1 deletion app/models/contract.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ class Contract < ActiveRecord::Base
belongs_to :chair
belongs_to :hiwi, class_name: 'User'
belongs_to :responsible, class_name: 'User'
has_many :time_sheets, -> { order(year: :desc, month: :desc) }
# If a contract is deleted, delete all of its dependent time sheets
has_many :time_sheets, -> { order(year: :desc, month: :desc) }, dependent: :destroy

validates_presence_of :start_date, :end_date, :chair, :hiwi, :responsible, :hours_per_week, :wage_per_hour
validates :hours_per_week, numericality: {greater_than: 0}
Expand Down
33 changes: 27 additions & 6 deletions spec/models/contract_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@
require 'rails_helper'

RSpec.describe Contract, type: :model do
before(:each) do
@sheet = FactoryGirl.create(:time_sheet)
@user = @sheet.user
@contract = @sheet.contract
end

context("scope for_user_in_month") do
context "scope for_user_in_month" do
before(:each) do
@sheet = FactoryGirl.create(:time_sheet)
@user = @sheet.user
@contract = @sheet.contract
end

it 'returns all contracts of a user in a given month and year' do
contract1 = FactoryGirl.create(:contract, start_date: Date.new(2016,1), end_date: Date.new(2016,3,15), hiwi: @user)
contract1 = FactoryGirl.create(:contract, start_date: Date.new(2016,3, 15), end_date: Date.new(2016,4), hiwi: @user)
Expand All @@ -32,4 +33,24 @@
expect(query.size).to eq(2)
end
end

context "deleting" do
before(:each) do
@hiwi = FactoryGirl.create(:hiwi)
start_date = Date.today << 1
end_date = Date.today >> 5
@contract = FactoryGirl.create(:contract, hiwi: @hiwi, start_date: start_date, end_date: end_date)
end

it 'is possible to delete a contract without time_sheets' do
expect { @contract.destroy }.to change { Contract.count }.from(1).to(0)
end

it 'deleting a contract also deletes all of its time sheets' do
@time_sheet = FactoryGirl.create(:time_sheet, contract: @contract, month: @contract.start_date.month)
expect(@contract.time_sheets.count).to eq(1)
expect { @contract.destroy }.to change { TimeSheet.count }.from(1).to(0)
expect(Contract.count).to eq(0)
end
end
end

0 comments on commit 54a52c9

Please sign in to comment.