最近开始做一个rails的项目,使用Cucumber 和 Rspec做BDD驱动开发。配置过程中发现很多细节容易出现问题,为了自己回头能记得,特此记录。
1. gems安装:以下是所有需要的gems
$ gem install cucumber-rails
$ gem install rspec
$ gem install rspec-rails
$ gem install database_cleaner
$ gem install gherkin
$ gem install capybara
$ gem install syntax
安装完毕以后,使用命令:gem list 查看已安装的gems,我的gems如下:
actionmailer ( 3.0 . 6 )
actionpack ( 3.0 . 6 )
activemodel ( 3.0 . 6 )
activerecord ( 3.0 . 6 )
activeresource ( 3.0 . 6 )
activesupport ( 3.0 . 6 )
arel ( 2.0 . 9 )
aruba ( 0.3 . 6 )
Ascii85 ( 1.0 . 0 )
builder ( 2.1 . 2 )
bundler ( 1.0 . 12 )
capybara ( 0.4 . 1.2 )
celerity ( 0.8 . 9 )
childprocess ( 0.1 . 8 )
cucumber ( 0.10 . 2 )
cucumber-rails ( 0.4 . 1 )
culerity ( 0.2 . 15 )
database_cleaner ( 0.6 . 6 )
diff-lcs ( 1.1 . 2 )
erubis ( 2.6 . 6 )
ffi ( 1.0 . 7 )
gherkin ( 2.3 . 5 )
i18n ( 0.5 . 0 )
json ( 1.5 . 1 )
json_pure ( 1.5 . 1 )
mail ( 2.2 . 15 )
mime-types ( 1.16 )
minitest ( 2.1 . 0 , 1.6 . 0 )
nokogiri ( 1.4 . 4 )
pdf-reader ( 0.9 . 1 )
polyglot ( 0.3 . 1 )
prawn ( 0.11 . 1 )
rack ( 1.2 . 2 )
rack-mount ( 0.6 . 14 )
rack-test ( 0.5 . 7 )
rails ( 3.0 . 6 )
railties ( 3.0 . 6 )
rake ( 0.8 . 7 )
rdoc ( 3.5 . 3 , 2.5 . 8 )
rspec ( 2.5 . 0 )
rspec-core ( 2.5 . 1 )
rspec-expectations ( 2.5 . 0 )
rspec-mocks ( 2.5 . 0 )
rspec-rails ( 2.5 . 0 )
rubygems-update ( 1.7 . 2 )
rubyzip ( 0.9 . 4 )
selenium-webdriver ( 0.1 . 4 )
sqlite3 ( 1.3 . 3 )
syntax ( 1.0 . 0 )
term-ansicolor ( 1.0 . 5 )
thor ( 0.14 . 6 )
treetop ( 1.4 . 9 )
ttfunk ( 1.0 . 1 )
tzinfo ( 0.3 . 26 )
xpath ( 0.1 . 3 )
完成后创建项目:
~ $ cd depot
使用-T来去除rails自带的测试目录
然后打开项目目录下的Gemfile,为其添加测试所需的gems:
gem 'cucumber' , " ~> 0.10.2 "
gem 'rspec' , " ~> 2.4 "
gem 'rspec-rails' , '~ > 2.5 '
gem 'cucumber-rails' , '~ > 0.4 . 1 '
gem 'capybara' , '~ > 0.4 . 1.2 '
gem 'database_cleaner' , '~ > 0.6 . 6 '
end
保存,然后在bash里对项目安装cucumber和rspec:
depot$rails generate cucumber :install
配置完成以后项目目录应有如下结构:
|-app /
|-config /
|-config . ru
|-db /
|-doc /
|-features /
|-Gemfile
|-Gemfile . lock
|-lib /
|-log /
|-public /
|-Rakefile
|-README
|-script /
|-spec /
|-tmp /
|-vendor /
根据BDD的原则,从feature开始开发,编写第一个.feature 文件:
Feature: Order
create new orders
Scenario :customer reads terms
Given I am on customer terms page
When I press " Create new order " button
Then I should be on new order page
保存后:
cucumber与spec应返回测试结果。至此cucumber和rspec配置完成。
需要注意的地方:
- 需注释掉features/step_definitions 目录下的web_steps.rb,此文件为模板文件,仅供编写时参考
- rake db:migrate 后还需 rake db:test:prepare
- 如配置正常,使用rails generate 生成时也会生成 rspec测试代码,放置于 spec目录下
- 测试所需的路径在 /features/support/paths.rb中编辑