概要
Factory Girlのインストール
詳細
インストール手順
gemの場合
gem install factory_girl
bundlerの場合 Gemfileに下記を追加。
factory_girlが本体。
factory_girl_railsはrailsの自動生成にfactory_girlの自動生成機能を追加します。
gem "factory_girl", "~> 4.2.0" gem "factory_girl_rails", "~> 4.2.1"
Factory格納用ディレクトリをspec配下に作成
mkdir factories
各種設定
specファイルでFactoryGirlを省略できるよう設定
config.include FactoryGirl::Syntax::Methods
サンプル
仕様
書籍管理システムの書籍情報の一覧表示のテストを想定します。
書籍モデルのファクトリーを自動生成
besrl g factory_girl:model book name:string isbn:string price:integer create spec/factories/books.rb
spec/factories/books.rb 自動生成直後
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :book do name "MyString" isbn "MyString" price 1 end end
ファクトリーの作成
2件の書籍データをファクトリ化しました
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :book1, :class => Book do name "The RSpec Book" isbn "9784798121932" price 4200 end factory :book2, :class => Book do name "リファクタリング:Rubyエディション" isbn "9784048678841" price 4800 end end
テスト対象コード
book_controller.rb
class BookController < ApplicationController def list @books = Book.find(:all) end end
テストからの呼び出し
book_controller_spec.rb
require 'spec_helper' require 'pp' describe BookController do describe "GET 'list'" do it "returns http success" do # => buildでファクトリを呼び出し。データは作成されない # @book1 = build(:book1) # @book2 = build(:book2) # => createでファクトリを呼び出し。データは作成される @book1 = create(:book1) @book2 = create(:book2) pp @book1 pp @book2 puts Book.all.size get 'list' response.should be_success end end end
テスト結果
$ be rspec ./spec/controllers/book_controller_spec.rb #<Book id: 7, name: "The RSpec Book", isbn: "9784798121932", price: 4200, created_at: "2013-07-15 14:06:05", updated_at: "2013-07-15 14:06:05"> #<Book id: 8, name: "リファクタリング:Rubyエディション", isbn: "9784048678841", price: 4800, created_at: "2013-07-15 14:06:05", updated_at: "2013-07-15 14:06:05"> 2 . Finished in 0.04426 seconds 1 example, 0 failures