iT邦幫忙

2021 iThome 鐵人賽

DAY 24
0
自我挑戰組

Rails測試寫起乃!!!系列 第 24

Day24 測試寫起乃 - Guard

Guard 可以幫助你在開發時監聽,並啟用測試,讓你在開發階段可以順便跑測試,當然我也是第一次玩XD

安裝 Guard

  gem 'guard'
  gem 'guard-rspec', require: false

並且 bundle install

產出 Guardfile
$ bundle exec guard init

執行 Guard
$ bundle exec guard

如果不想要一直輸入 bundle exec

可以下 bundle binstub guard 會在專案中產出 bin/guard 的檔案

之後下 bin/guard 等同於 bundle exec guard

初始化 guard-rspec 將其指令置入 Guardfile

guard :rspec, cmd: "bundle exec rspec" do
  require "guard/rspec/dsl"
  dsl = Guard::RSpec::Dsl.new(self)

  # Feel free to open issues for suggestions and improvements

  # RSpec files
  rspec = dsl.rspec
  watch(rspec.spec_helper) { rspec.spec_dir }
  watch(rspec.spec_support) { rspec.spec_dir }
  watch(rspec.spec_files)

  # Ruby files
  ruby = dsl.ruby
  dsl.watch_spec_files_for(ruby.lib_files)

  # Rails files
  rails = dsl.rails(view_extensions: %w(erb haml slim))
  dsl.watch_spec_files_for(rails.app_files)
  dsl.watch_spec_files_for(rails.views)

  watch(rails.controllers) do |m|
    [
      rspec.spec.call("routing/#{m[1]}_routing"),
      rspec.spec.call("controllers/#{m[1]}_controller"),
      rspec.spec.call("acceptance/#{m[1]}")
    ]
  end

  # Rails config changes
  watch(rails.spec_helper)     { rspec.spec_dir }
  watch(rails.routes)          { "#{rspec.spec_dir}/routing" }
  watch(rails.app_controller)  { "#{rspec.spec_dir}/controllers" }

  # Capybara features specs
  watch(rails.view_dirs)     { |m| rspec.spec.call("features/#{m[1]}") }
  watch(rails.layouts)       { |m| rspec.spec.call("features/#{m[1]}") }

  # Turnip features and steps
  watch(%r{^spec/acceptance/(.+)\.feature$})
  watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) do |m|
    Dir[File.join("**/#{m[1]}.feature")][0] || "spec/acceptance"
  end
end

接下來執行 bin/guard 打開監聽

接著你只要到哪個 controller 修改code他就會立即幫妳執行此controller的rspec

# 若我修改 models/collection.rb 他就會跑
13:41:21 - INFO - Running: spec/models/collection_spec.rb
...

Finished in 0.73355 seconds (files took 4.14 seconds to load)
3 examples, 0 failures

#修改 collections_controller.rb
13:42:18 - INFO - Running: spec/controllers/collections_controller_spec.rb
...

Finished in 0.62857 seconds (files took 3.78 seconds to load)
3 examples, 0 failures

其實也是挺方便的,可以的話希望未來能夠講一些客製化方面的東西只是初步研究而已!


上一篇
Day23 測試寫起乃 - Spork
下一篇
Day25 測試寫起乃 - spring-command-rspec
系列文
Rails測試寫起乃!!!30

尚未有邦友留言

立即登入留言