Ruby-on-rails 如何在 rspec 测试中输出变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6025803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:10:03  来源:igfitidea点击:

How do I output a variable in a rspec test?

ruby-on-railsrspec

提问by double free

Is there a quick way to output the value of variable in a rspec test? Something like this for example, in a controller to output a variable, I do:

有没有一种快速的方法可以在 rspec 测试中输出变量的值?例如,像这样的东西,在控制器中输出一个变量,我这样做:

raise variable.to_yaml

Is there something similar I can do in a rspec test to see the contents of a variable?

我可以在 rspec 测试中做类似的事情来查看变量的内容吗?

回答by ipd

If you want the output to go into the log file (i.e. logs/test.log), you can use the rails logger.

如果您希望输出进入日志文件(即 logs/test.log),您可以使用 rails 记录器。

Rails.logger.debug variable.inspect
Rails.logger.debug variable.to_yaml

If you want to see the output in the console, you can use the pretty printer 'pp'.

如果要在控制台中查看输出,可以使用漂亮的打印机“pp”。

require 'pp'

it 'does something'
  thing = Factory(:something)
  pp thing
end

Or you can use good 'ol puts

或者你可以使用好的 'ol puts

puts thing.to_yaml

回答by Puce

At this moment (Rails 4) you can log it:

此时(Rails 4)您可以记录它:

p variable

p variable

回答by knagode

Use this:

用这个:

$stderr.puts variable.to_yaml

回答by AYOUB_MZ

You can use the gem pry to do this

您可以使用 gem pry 来执行此操作

  1. add gem "pry" in your gemfile
  2. bundle install
  1. 在您的 gemfile 中添加 gem "pry"
  2. bundle install

Now you can any test any variable by putting "binding.pry" just after that variable. Run bundle exec rspec filepathand you will get something like rails c, then write directly your variable.

现在您可以通过在该变量之后放置“binding.pry”来测试任何变量。运行bundle exec rspec filepath,你会得到类似 rails c 的东西,然后直接写你的变量。

I hope it makes sense

我希望这是有道理的