I have this table called Group
.
class Group < ApplicationRecord
belongs_to :admin, class_name: "User", foreign_key: :admin_id
has_many :memberships, dependent: :destroy
has_many :users, through: :memberships
has_many :tasks, dependent: :destroy
has_many :tags, dependent: :destroy
has_many :invitations, dependent: :destroy
end
I am creating some tests for when I delete a group. After deleting a group I want to check that the group is deleted and that the associated records are deleted as well.
it "deletes the group" do
expect(Group.find(group.id)).to_not be_present
end
it "deletes the group's dependent associations" do
expect(Task.where(group: group).count).to eq 0
expect(Tag.where(group: group).count).to eq 0
expect(Invitation.where(group: group).count).to eq 0
expect(Membership.where(group: group).count).to eq 0
end
I wrote it like that but it feels really repetitive. I was wondering if there is another way to create a query to get all the associated records in an array and check if the array is empty.
I tried with connected where
like this:
Task.where(group: g).and(Tag.where(group: g)).and(Membership.where(group: g)).and(Invitation.where(group: g))
But it is throwing the following error: (Object doesn't support #inspect)
I read about joins
but couldn’t understand it properly so I am not sure if it is the right direction to go to.
Any help would be appreciated. Thank you!
PD: I am using PostgreSQL for the db
4
Answers
This is not a task for table joining since these tables have nothing to be joined on when the group is deleted.
You can remove the repetition by calling the
expect
in a loop:I would not test this behavior because it only tests the implementation provided by Ruby on Rails and Rails methods are already tested in the framework internally.
When you really want to test your implementation, then I would suggest adding the
shoulda-matcher
gem and test that the associations are configured as expected, like this:To test behavior, I believe it’s best to test one by one. But, in general, following good practices, instead of an it with several expectations, the best thing is an it for each expectation.
You can use below to get all associations on record class
It will give you an array of associations. Sample association-
You can also use the
reflect_on_association
method to fetch details for a specific association