ruby-on-railsrunit

Rails5 - what is the best approach for writing unit tests for services?


In my app i have serveral services (pure ruby). what is the best approach to implement unit tests? shoiuld i implement additional unit tests for controllers, or create a separated tests only for services?

update - implemented solution:

  1. dedicated tests for UserService (test/services/user_service_test
  2. unit test for creating new employee includes verification if UserService.create_user_for_employee method is called. Test is based on Minitest::Mock. It requires 'minitest/autorun' (require 'minitest/autorun' in test_helper)

EmployeesControllerTest:

setup do
    #@employee = employees(:one)
    @new_employee = {name: 'name', surname: 'surname', email: 'email@email.com'}
    sign_in users(:admin1)
    @mock = UserService.new
  end

test "should create_employee" do
    assert_difference('Employee.count') do
      post employees_url, employee: @new_employee
    end

    @mock.stub :create_user_for_employee, true do
        assert(@mock.create_user_for_employee(@new_employee, 'user'))
    end

    assert_redirected_to employees_url
  end

Solution

  • You probably have simple ruby classes inside your /app/services folder. Then just write very simple unit test for each single service. Place them under /test/services/ or spec/services/ folder. You should have one unit test file for each class you define for your application.