Rspec测试

来源:互联网 发布:中国美术出版总社 知乎 编辑:程序博客网 时间:2024/05/17 06:30
#gem


rspec-rails


Capybara      允许使用类似英语中的句法编写模拟与应用程序交互的代码


guard-rspec


spork


Factory Girl  预构件创建用户对象更方便,存入数据库也更容易。


###
$rake generate spec:install   让 generate生成 RSpec 测试用例


$rake generate intergration_test  static_pages
  invoke  rspec
  create    spec/requests/static_pages_spec.rb


require 'spec_helper'


describe "Static pages" do


  describe "Home page" do


    it "should have the content 'Sample App'" do
      visit '/static_pages/home'
      page.should have_content('Sample App')
    end
  end
end
读起来很像英语,这是因为 RSpec 利用了 Ruby 语言的延展性定义了一套“领域专属语言”(Domain-specific Language, DSL)用来写测试代码。重要的是,如果你想使用 RSpec 不是一定要知道 RSpec 的句法。初看起来是有些神奇,RSpec 和 Capybara 就是这样设计的


使用 rspec 命令有一点很烦人,你总是要切换到命令行然后手动输入命令执行测试。(另一个很烦人的事情是,测试的启动时间很慢),使用 Guard 自动运行测试,Guard 会监视文件系统的变动,假如你修改了 static_pages_spec.rb,那么只有这个文件中的测试会被运行。
使用guard
初始化 Guard,这样它才能和 RSpec 一起使用
$guard init rspec
  Writing new Guardfile to /Users/mhartl/rails_projects/sample_app/Guardfile
  rspec guard added to Guardfile, feel free to edit it


 加入默认 Guardfile 的代码
require 'active_support/core_ext'


guard 'rspec', :version => 2, :all_after_pass => false do
  .
  .
  .
  watch(%r{^app/controllers/(.+)_(controller)\.rb$})  do |m|
    ["spec/routing/#{m[1]}_routing_spec.rb",
     "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb",
     "spec/acceptance/#{m[1]}_spec.rb",
     (m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" :
                       "spec/requests/#{m[1].singularize}_pages_spec.rb")]
  end
  watch(%r{^app/views/(.+)/}) do |m|
    (m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" :
                       "spec/requests/#{m[1].singularize}_pages_spec.rb")
  end
  .
  .
  .
end




运行  rspec 时你或许已经察觉到了,在开始运行测试之前有好几秒的停顿时间,一旦测试开始就会很快完成。这是因为每次 RSpec 运行测试时都要重新加载整个 Rails 环境。Spork 测试服务器可以解决这个问题。Spork 只加载一次环境,然后会为后续的测试维护一个进程池。
$spork
在另一个命令行窗口中,运行测试组件,并指定 --drb(distributed Ruby,分布式 Ruby)选项,验证一下环境的加载时间是否明显的减少了
$rspec spec/requests/static_pages_spec.rb --drb
RSpec 让其自动使用 Spork
vim .rspec 加入下面两行
--colour
--drb


Spork 结合 Guard使用就更强大了,使用如下的命令设置
$guard init spork


同时修改 Guardfile 加入 
require 'active_support/core_ext'


guard 'spork', :rspec_env => { 'RAILS_ENV' => 'test' } do
  watch('config/application.rb')
  watch('config/environment.rb')
  watch(%r{^config/environments/.+\.rb$})
  watch(%r{^config/initializers/.+\.rb$})
  watch('Gemfile')
  watch('Gemfile.lock')
  watch('spec/spec_helper.rb')
  watch('test/test_helper.rb')
  watch('spec/support/')
end


guard 'rspec', :version => 2, :all_after_pass => false, :cli => '--drb' do
  .
  .
  .
end



修改了 guard 的参数,包含了 :cli => --drb,这可以确保 Guard 是在 Spork 服务器的命令行界面(Command-line Interface, cli)中运行的。
修改完之后,我们就可以通过 guard 命令同时启动 Guard 和 Spork了。







0 0
原创粉丝点击