在spec/fixtures目录下存放固定对象
# spec/fixtures/movies.yml
milk_movie:
id: 1
title: Milk
rating: R
release_date: 2008-11-26
documentary_movie:
id: 2
title: Food, Inc.
release_date: 2008-09-07
新建spec/models/movie_spec.rb
require 'rails_helper'
describe Movie do
fixtures :movies
it 'should include rating and year in full name' do
movie = movies(:milk_movie)
expect(movie.title).to eql('Milk')
expect(movie.rating).to eql('R')
end
end
书中的factory_girl已改名为factory_bot.
https://github.com/thoughtbot/factory_bot
在Gemfile, test块下添加factory_bot_rails和rspec-its(为使用its),并执行bundle install
group:test
gem 'factory_bot_rails'
gem 'rspec-its'
使用Factory,文件spec/factories/movie.rb
# spec/factories/movie.rb
FactoryBot.define do
factory :movie do
title {'A Fake Title'} # default values
rating {'PG'}
release_date { 10.years.ago }
end
end
文件spec/models/movie_spec.rb,我们测试一个尚未实现的方法name_with_rating
require 'rails_helper'
require 'spec_helper'
describe Movie do
it 'should include rating and year in full name' do
# 'build' creates but doesn't save object; 'create' also saves it
movie = FactoryBot.build( :movie, :title => 'Milk', :rating => 'R')
expect(movie.title).to eql('Milk')
expect(movie.name_with_rating).to eql('Milk (R)')
end
end
# More concise: uses Alternative RSpec2 'subject' syntax', and mixes in
# FactoryGirl methods in spec_helper.rb (see FactoryGirl README)
describe Movie do
subject do
Movie.new(:title => 'Milk', :rating => 'R')
end
its(:title) { is_expected.to eql('Milk') }
end