TDD-based

공동가계부








 2013-10-16

최 효 성

Gemfile


group :test do
  gem 'coveralls', require: false
  gem 'factory_girl_rails', :require => false
  gem 'faker'
  gem 'database_cleaner', '=1.0.1'   # Clean database between tests
  gem 'rspec-rails'                  # Test framework
  gem 'shoulda'                      # nice rspec matchers
end
group :development, :test do
  gem 'fabrication'                  # Test object generation
  gem 'spring'
  gem 'guard-rspec' end

Autogeneration of Rspec

in app/application.rb
module Bbapi
  class Application < Rails::Application
    config.generators do |g|
      g.test_framework :rspec
    end   end
end

Gems


RSPEC Installation


  $ rails generate rspec:install

The generator creates a few files. Namely:.rspec - a config file where we can store extra command line options for the rspec command line tool. By default it contains --colour which turns on colored output from RSpec.spec - a directory that will store all of the various model, controller, view, acceptance and other specs for your appspec/spec_helper.rb - a file that's loaded by every spec (not in any automatic way but most have require 'spec_helper' at the top). It sets the test environment, contains app level RSpec configuration items, loads support files, and more.

Rspec Generators

rails generate rspec:model widget
will create a new spec file in spec/models/widget_spec.rb.

Other Rspec Generator :

  • scaffold
  • model
  • controller
  • helper
  • mailer
  • observer
  • integration

Directory Hierarchy of Spec




spec 디렉토리는 app 디렉토리와 같은 구조를 가진다.

New Rspec Syntax


in June, 2012
"should" 를 대체하는 함수 : "expect( )"

from :
it "is true when true" do
  true.should be_true
end 

to :

it "is true when true" do
  expect(true).to be_true
end 



"Factory_girl"


    • 레일스의 디폴트 fixtures (테스트 데이터)를 대신사용
    • 액티브레코드를 이용하여 데이터를 테스트한다.

fixtures (e.g. contacts.yml)

1 aaron:
2   firstname: "Aaron"
3   lastname: "Sumner"
4   email: "aaron@everydayrails.com"
5 
6 john:
7   firstname: "John"
8   lastname: "Doe"
9   email: "johndoe@nobody.org" 


factories

spec/factories/contacts.rb
1 FactoryGirl.define do
2   factory :contact do
3     firstname "John"
4     lastname "Doe"
5     sequence(:email) { |n| "johndoe#{n}@example.com"}
6   end
7 end 

       example:

contact = FactoryGirl.build(:contact, firstname: nil) 
       Simplifying (in spec/spec_helper.rb)
1 RSpec.configure do |config|
2   # Include Factory Girl syntax to simplify calls to factories
3   config.include FactoryGirl::Syntax::Methods
4 
5 end 

"Fake"


  • 짝퉁 데이터(진짜같은 테스트 데이터)를 생성해 준다.
  • 데이터베이스에 저장
  • $ gem install fake
 Faker::Name.name      #=> "Christophe Bartell"
 Faker::Internet.email #=> "kirsten.greenholt@corkeryfisher.info"  
           More Examples
          : Company /Internet / Lorem / Name / Phone Number /Address

Demo

TDD 

By Hyoseong Choi

TDD 

  • 1,605