您的位置:首页 > 其它

Rspec 使用笔记

2012-07-10 20:00 330 查看
打算以后使用rspec 就行测试开发,由于第一次在项目中使用,所以,记录再次,便于以后查询

本文的记录参考了开源软件 angle-nest 和 Ruby-China源码

安装gem

group :development,  :test do
  gem 'cucumber-rails', :require => false
  gem 'database_cleaner'
  gem 'factory_girl'
  gem 'factory_girl_rails'
  gem 'rspec-rails'
  gem 'capybara'
  gem 'delorean'
end


install

rails generate rspec:install


运行测试

rake spec


修改helper文件

config.mock_with :rspec
  config.use_transactional_fixtures = false

  config.include Delorean

  DatabaseCleaner.strategy = :truncation
  config.before do
    DatabaseCleaner.clean
  end


安装watchr

gem 'watchr'


新建.watchr文件

def run_spec(file)
  unless File.exist?(file)
    puts "#{file} does not exist"
    return
  end 

  puts "Running #{file}"
  system "bundle exec rspec #{file}"
  puts
end

watch("spec/.*/*_spec.rb") do |match|
  run_spec match[0]
end

watch("app/(.*/.*).rb") do |match|
  run_spec %{spec/#{match[1]}_spec.rb}
end


解析

一旦spec/目录下有以_spec.rb结尾的文件发生了改变,watchr便会自动运行run_spec 方法来对该文件进行测试。
    一旦有app/目录下有.rb结尾的文件发生了改变,立即调用run_spec 方法来执行该文件所对应的spec测试文件。
    run_file 通过文件名来检查spec文件是否存在, 然后来运行该spec (调用 system)


运行

watchr .watchr


增加spark提升速度

gem 'spork', '1.0.0rc3'


运行

spork --bootstrap


修改spec_helper.rb

第一,上传 rubygems,因为我们已经有bundler了

修改spec_helper.rb文件如下

require 'spork'
#uncomment the following line to use spork with the debugger
#require 'spork/ext/ruby-debug'

Spork.prefork do
  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'
  require 'rspec/autorun'

  # Requires supporting ruby files with custom matchers and macros, etc,
  # in spec/support/ and its subdirectories.
  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

  RSpec.configure do |config|
    config.mock_with :rspec
    config.use_transactional_fixtures = false
    config.include Delorean

    DatabaseCleaner.strategy = :truncation
    config.before do 
      DatabaseCleaner.clean
    end
  end
end

Spork.each_run do
  # This code will be run each time you run your specs.

end


修改.rspec文件,增加如下代码

--drb

运行spork

spork


在运行 watchr .wtachr 速度加快了

清除test环境下的缓存,编辑
config/environments/test.rb


config.cache_classes = false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: