TDD 를 위한 Rails 테스트

Rails에서 TDD를 효율적으로 수행하기 위한 테스트 함수 선언, assert/assert_not 활용, 테스트 종류, Fixture 사용법, 그리고 테스트 실행 방법에 대해 자세히 알아봅니다.

1. 테스트 함수 선언 방법

 

  test "the truth" do

    와

  def test_the_truth

 

모두 혼용해서 사용 가능하다.

 

2. assert 와 assert_not

 

- assert : 성공해야지 정상적인 케이스로 분류된다.

- assert_not : 실패해야 정상적인 케이스로 분류된다.

  (모델의 attribute가 nil 값으로 저장되면 안될 경우, assert_not post.save) 등과 같은 방식으로 작성

 

3. 테스트의 종류

 

- 테스트의 종류는 크게 model_test, controller_test, integration_test 로 나눌 수 있다.

- model, controller 테스트는 각각의 모델, 컨트롤러를 생성할 때 나타나지만, integration test 는 개발자가 따로 생성해 주어야 한다.

rails g integration_test test_name 의 명령어로 생성한 후, 원하는 로직을 작성한다.

 

require 'test_helper'



class CanCreatePostTest < ActionDispatch::IntegrationTest

  test "can create" do

    get "/api/v1/posts"

    assert_response :success



    post "/api/v1/posts", params: { title: "example title", content: "example content" }

    assert_response :success

    body = JSON.parse(response.body)

    assert_equal "example title", body["title"]



  end

end

 

require 'test_helper'



class PostCreateTest < ActionDispatch::IntegrationTest

  include Devise::Test::IntegrationHelpers



  test "post create" do

    sign_in users(:one)

    get '/posts'

    assert_response :success

    get '/posts/new'

    assert_response :success

    user = users(:one)

    post '/posts', params: { 

      post: { user_id: user.id, title: "example", content: "example content" } 

    }

    assert_redirected_to posts_path, "게시물 저장 실패."



  end

end

 

4. Fixture 사용

 

- 테스트 할 때, 가상의 데이터베이스 레코드들이 필요하다. 이 때 fixture 이 사용된다. fixture 디렉토리 안의 모델이름.yml 에 테스트케이스에 사용될 모델 레코드들을 작성해 주면 된다.

- test 파일에서 픽스처를 사용할 때에는 model_names(:instance_name) 의 꼴로 사용하면 된다.

- Fixture 파일 예시

(posts.yml)

 

post1:

  user: users(:user1)

  title: Test title1

  content: Test Content1

 

- 테스트 파일에서 픽스처 호출하기

comment.post_id = posts(:post1).id

 

5. 테스트 실행 방법

 

- rails test : 전체 테스트 실행

- rails test/models : 모델 테스트 실행 (이와 비슷하게 controller 등도 따로 분리해서 실행할 수 있다.)

- rails test/models/post_test.rb -n test_the_truth : post_test.rb 의 test_the_truth 함수만을 테스트 함

 

* 공식 문서

 

https://guides.rubyonrails.org/testing.html


이것도 읽어보세요