gem install factory_girl

时间:2023-11-11 21:58:38

文章是从个人博客转过来的,  可以直接访问 iwangzheng.com

https://github.com/thoughtbot/factory_girl

https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

http://ruby.taobao.org/

今天项目结束,打算搞一下接手这个项目之前的单元测试,因为接受的时候很多测试是跑不通的,于是重新学习了一下 factory_girl

gem install factory_girl (半天没响应)

由于国内网络原因(你懂的),导致 rubygems.org 存放在 Amazon S3 上面的资源文件间歇性连接失败。所以你会与遇到 gem install rack 或 bundle install 的时候半天没有响应,具体可以用 gem install rails -V 来查看执行过程。现在来更换一下gem source

$ gem sources --remove https://rubygems.org/
$ gem sources -a http://ruby.taobao.org/
$ gem sources -l
*** CURRENT SOURCES *** http://ruby.taobao.org
# 请确保只有 ruby.taobao.org

Configure your test suite

# rspec
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end # Test::Unit
class Test::Unit::TestCase
include FactoryGirl::Syntax::Methods
end # Cucumber
World(FactoryGirl::Syntax::Methods) # Spinach
class Spinach::FeatureSteps
include FactoryGirl::Syntax::Methods
end # MiniTest
class MiniTest::Unit::TestCase
include FactoryGirl::Syntax::Methods
end # MiniTest::Spec
class MiniTest::Spec
include FactoryGirl::Syntax::Methods
end # minitest-rails
class MiniTest::Rails::ActiveSupport::TestCase
include FactoryGirl::Syntax::Methods
end 由于我们用的是rspec,所以选第一种,所在spec/spec_helper.rb里配置第18行那句

1 # -*- encoding : utf-8 -*-
2 # This file is copied to spec/ when you run 'rails generate rspec:install'
3 ENV["RAILS_ENV"] ||= 'test'
4 require File.expand_path("../../config/environment", __FILE__)
5 require 'rspec/rails'
6 require 'rspec/autorun'
7 require "email_spec"
8
9 # Requires supporting ruby files with custom matchers and macros, etc,
10 # in spec/support/ and its subdirectories.
11 Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
12 Dir[Rails.root.join("lib/mock*.rb")].each {|f| require f}
13
14 RSpec.configure do |config|
15 config.fixture_path = "#{::Rails.root}/spec/fixtures"
16 config.use_transactional_fixtures = true
17 config.infer_base_class_for_anonymous_controllers = false
18 config.include FactoryGirl::Syntax::Methods
19 config.global_fixtures = :all
20 config.include(EmailSpec::Helpers)
21 config.include(EmailSpec::Matchers)
22 end

Defining factories

# This will guess the User class
FactoryGirl.define do
factory :user do
first_name "John"
last_name "Doe"
admin false
end # This will use the User class (Admin would have been guessed)
factory :admin, class: User do
first_name "Admin"
last_name "User"
admin true
end
end

一般在factories的文件夹,以modle名字来命名factory,这样更清晰

来看看我写的这段

FactoryGirl.define do
    factory :cms_tv_version do
       title "2.0.0"
       state 1
    end
end