当普通的 Ruby(不是 Rails)文件更改时自动运行 RSPec [英] Automatically run RSPec when plain-old Ruby (not Rails) files change
问题描述
我正在编写一个旨在从命令行运行的 Ruby 脚本.该脚本有一个相应的 RSpec 文件来验证其功能.文件夹结构为:
I am writing a Ruby script designed to run from the command line. The script has a corresponding RSpec file that verifies its functionality. The folder structure is:
./main_script.rb
./spec/main_script_spec.rb
在顶级目录中运行 rspec spec
可以正常工作.显示了来自 ./spec/main_script_spec.rb
文件的测试结果.我想避免每次更改主脚本文件或规范文件时手动运行它.我所有的搜索结果都出现了诸如 guard 之类的东西(据我所知)都是经过设计的用于 Rails 应用程序.
Running rspec spec
in the top level directory works as expected. Test results from the ./spec/main_script_spec.rb
file are shown. I'd like to avoid running this manually every time I change either the main script file or the spec file. All my search results turn up things like guard which (as far as I can tell) are all designed for Rails apps.
如何设置 RSpec 以监视脚本或规范更改并使用非 Rails Ruby 代码自动运行?
How do I setup RSpec to watch for script or spec changes and run automatically with non-Rails Ruby code?
推荐答案
正如 David 所说,Guard 可用于监视各种文件并在这些文件被修改时执行操作.它不必与 Rails 应用程序一起使用.我过去使用 guard
设置了类似的东西.这是我所做的:
Like David said, Guard can be used to watch a wide variety of files and perform actions when those files are modified. It does not have to be used with a Rails app. I have set up something similar in the past using guard
. Here is what I did:
将以下内容放入您的 Gemfile
:
Place the following in your Gemfile
:
source 'https://rubygems.org'
gem 'guard'
gem 'guard-shell'
gem 'rspec'
gem 'rb-fsevent', '~> 0.9'
然后运行:
$ bundle install
在您的主目录中创建一个 Guardfile:
Create a Guardfile in your home directory with:
$guard init
在 Guardfile
中,注释掉示例并添加:
In the Guardfile
, comment out the examples and add this:
guard :shell do
watch(%r{^*\.rb}) { `bundle exec rspec spec/` }
end
这告诉守卫监视目录中任何 ruby 文件的修改,并在它们更改时执行命令 bundle exec rspec spec/
(反引号用于在 shell 中执行命令).
This tells guard to watch for modifications to any ruby files in the directory and execute the command bundle exec rspec spec/
when they change (the backticks are used to execute the command in the shell).
然后在当前目录中打开一个新的终端窗口并启动一个 guard
服务器以开始查看文件:
Then open up a new terminal window in your current directory and start a guard
server to start watching the files:
$ bundle exec guard
现在,当您修改目录中的 ruby 文件时,您的 Rspec 测试套件应该会自动运行.
Now your Rspec test suite should automatically run when you modify ruby files in the directory.
这篇关于当普通的 Ruby(不是 Rails)文件更改时自动运行 RSPec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!