当从 Ruby 脚本作为命令 %x[rspec] 运行时,如何将 RSpec 输出到控制台?
我有一个带有实例方法的类,该类使用 %x[]
表示法运行 RSpec:
class TestRunner
def run_rspec
# do stuff
%x[rspec spec -c -f documentation]
# do more stuff
end
end
当我这样做时:
> tr = TestRunner.new
> tr.run_rspec
文档(组和示例名称)不会出现在控制台中。
相比之下,当我直接从命令行运行 rspec
时,我得到:
$ rspec spec -c -f documentation
a group name
an example
another example
...
我不想要这样做:
puts %x[rspec spec -c -f documentation
因为这样输出就会全部吐出一大堆在最后。我希望它“实时”运行,每个示例都会在每个测试运行时显示。
有没有办法,通过我的设置,让 RSpec 宣布它正在做什么(就像从命令行正常运行时一样)?
I have a class with an instance method that runs RSpec using the %x[]
notation:
class TestRunner
def run_rspec
# do stuff
%x[rspec spec -c -f documentation]
# do more stuff
end
end
When I do this:
> tr = TestRunner.new
> tr.run_rspec
The documentation (group and example names) does not appear in the console.
To contrast, when I run rspec
straight from the command line I get this:
$ rspec spec -c -f documentation
a group name
an example
another example
...
I don't want to do this:
puts %x[rspec spec -c -f documentation
Because then the output all spits out in one huge clump at the very end. I want it to run in "real time," with each example showing up as each test is run.
Is there a way, with the setup I have, to get RSpec to announce what it's doing, as it's doing it (as it does when run normally from the command line)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我被告知
system()
和其他 shell 方法使用起来可能很危险,所以我选择切换到使用 RSpec 本身的更好方法:而不是通过调用它我的 Ruby 脚本中的 shell。
Ruby 提供了多种从命令行运行程序的选项。我使用的是
%x[]
,这对于我的用例来说是错误的选择。解决方案:使用
system()
,而不是%x[]
——rspec
将写入STDOUT
当我使用system('rspec spec')
调用它时实时进行。一些背景知识,以防对偶然发现这个问题的人有帮助:
考虑 Ruby 命令行选项之间的差异:
%x[command]
累积command
的结果并返回它,一大块。exec('command')
将在command
运行时输出command
,但会替换调用它的任何进程 - 即,如果您使用exec
在您的 Ruby 脚本中,您的 Ruby 脚本将无法完成。system('command')
在子 shell 中执行command
,并返回到调用脚本。这就是为什么我的脚本选择
system
的原因。I've been advised that
system()
and the other shell methods can be dangerous to use, so I've opted to switch to the even-better approach of using RSpec itself:rather than calling it via shell from my Ruby script.
Ruby offers several options for running programs from the command line. I was using
%x[]
, the wrong choice for my use case.Solution: Use
system()
, not%x[]
--rspec
will write toSTDOUT
in real-time when I call it withsystem('rspec spec')
.Some background in case it's helpful to anyone who stumbles upon this question:
Consider the differences between Ruby's command-line options:
%x[command]
accumulates the result ofcommand
and returns it, in one chunk.exec('command')
will outputcommand
ascommand
runs, but will replace whatever process called it -- i.e., if you useexec
in your Ruby script, your Ruby script won't finish.system('command')
executescommand
in a subshell, and returns to the calling script.This is why
system
was the choice for my script.