Rspec 使用笔记

打算以后使用rspec 就行测试开发,由于第一次在项目中使用,所以,记录再次,便于以后查询

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

  1.  安装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
    



  2. install

    rails generate rspec:install


  3. 运行测试
    rake spec

  4. 修改helper文件
      config.mock_with :rspec
      config.use_transactional_fixtures = false
    
      config.include Delorean
    
      DatabaseCleaner.strategy = :truncation
      config.before do
        DatabaseCleaner.clean
      end
    

  5. 安装watchr
    gem 'watchr'

  6. 新建.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)
    



  7. 运行
    watchr .watchr

  8. 增加spark提升速度
    gem 'spork', '1.0.0rc3'

  9. 运行
    spork --bootstrap

  10. 修改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

  11. 修改.rspec文件,增加如下代码
    --drb
  12. 运行spork
    spork

  13. 在运行 watchr .wtachr  速度加快了
  14. 清除test环境下的缓存,编辑 config/environments/test.rb
    config.cache_classes = false








你可能感兴趣的:(Rspec 使用笔记)