2
\$\begingroup\$

I know how to write simple RSpec tests and unit tests. I just want to know if this is good enough or if there are any improvements I can make.

I intend to test the the toggle_property method of the TaskItemUserReference model which updates the property, completed from false to true or vice versa.

Relationships

User has many Tasks through TaskUserReference Task has many Users through TaskUserReference

TaskItem has many Users through TaskItemUserReference User has many TaskItem through TaskItemUserReference

#Factories

FactoryGirl.define do
  factory :task do
    name Faker::Lorem.sentence(2)
  end
end

FactoryGirl.define do
  factory :task_user_reference do
    user
    task
  end
end

FactoryGirl.define do
  factory :task_item do
    name Faker::Lorem.sentence(3)
    task
  end
end

FactoryGirl.define do
  factory :task_item_user_reference do
    task_item
    user
    active true
    completed false
  end
end

# RSPEC test
require "rails_helper"

RSpec.describe Task, type: :model do

  let(:owner) { create(:user) }
  let(:task) { create(:task, owner: owner) }
  let(:user) { create(:user) }
  let(:task_item) { create(:task_item, task: task) }

  before do
    user.tasks << task
    user.task_item_user_references.create(
      user_id: user.id,
      completed: true,
      task_item: task_item
    )
  end

  describe "task_items" do
    it "updates status" do
      task_item_user_reference = user.task_item_user_references.first
      task_item_user_reference.toggle_property(:completed)

      expect(task_item_user_reference.completed).to eq(false)
     end
  end
end
\$\endgroup\$
1
\$\begingroup\$

It looks like you don't need the whole user-task-task item setup for the test you provided. It's actually a TaskItemUserReference spec, not Task spec.

RSpec.describe TaskItemUserReference, type: :model do

  describe "#toggle_property" do
    it "updates property" do
      task_item_user_reference = TaskItemUserReference.new(completed: true)

      expect do 
        task_item_user_reference.toggle_property(:completed)
      end.to change {task_item_user_reference.completed}.from(true).to(false)
    end
  end
end
\$\endgroup\$
  • \$\begingroup\$ TaskItemUserReference seems to make sense. \$\endgroup\$ – Thorpe Obazee Aug 27 '17 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.