How do I output a variable in a rspec test? - ruby-on-rails

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:
raise variable.to_yaml
Is there something similar I can do in a rspec test to see the contents of a variable?

If you want the output to go into the log file (i.e. logs/test.log), you can use the rails logger.
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'.
require 'pp'
it 'does something'
thing = Factory(:something)
pp thing
end
Or you can use good 'ol puts
puts thing.to_yaml

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

Use this:
$stderr.puts variable.to_yaml

You can use the gem pry to do this
add gem "pry" in your gemfile
bundle install
Now you can any test any variable by putting "binding.pry" just after that variable. Run bundle exec rspec filepath and you will get something like rails c, then write directly your variable.
I hope it makes sense

Related

How to run script before every Rails console invocation?

I'm pretty tired of writing this line every time I want to open the Rails console:
irb(main):001:0> ActsAsTenant.current_tenant = User.find(1).account
Is there any way to run command/script before every "rails c"/"irb" invocation?
Thanks in advance!
Put the code you want to execute into .irbrc file in the root folder of your project:
echo 'ActsAsTenant.current_tenant = User.find(1).account' >> .irbrc
bundle exec rails c # ⇐ the code in .irbrc got executed
Sidenote: Use Pry instead of silly IRB. Try it and you’ll never roll back.
I wrote an extended answer to this in another question but the short answer is that if you are using Rails 3 or above you can use the console method on YourApp::Application to make it happen:
module YourApp
class Application < Rails::Application
...
console do
ActsAsTenant.current_tenant = User.find(1).account
end
end
end
You could put your setup code in a rb file, for example:
foo.rb:
def irb_setup
ActsAsTenant.current_tenant = User.find(1).account
end
launch irb like this:
irb -r ./foo.rb
and call the method (which will autocomplete pressing tab)
2.3.0 :001 > init_irb
In fact maybe you could put the code directly, without any method, and it would be executed when it is loaded. But I'm not sure if that would work or mess with the load order.

How to run code automatically when launching a Rails console?

Let's say I wanted a greeting every time the Rails console comes up:
Scotts-MBP-4:ucode scott$ rails c
Loading development environment (Rails 4.2.1)
Hello there! I'm a custom greeting
2.1.5 :001 >
Where would I put the puts 'Hello there! I\'m a custom greeting' statement?
Another Stackoverflow answer suggested, and I've read this elsewhere too, that I can put that in an initializer like this:
# config/initializers/console_greeting.rb
if defined?(Rails::Console)
puts 'Hello there! I\'m a custom greeting'
end
That doesn't work for me though :(. Even without the if defined?(Rails::Console) I still don't get output. Seems like initializers are not run when I enter a console, despite what others suggest.
I use ~/.irbrc for similar purposes (I require a gem in each console session). For example, my .irbrc
if (defined? Rails)
# Rails specific
end
# common for all irb sessions
You could use your project name to limit executing code to only one project's console:
if (defined? Rails) && (defined? YourProject)
# code goes here
end
The following will work in Rails 6:
Just pass a block to Rails.application.console, e.g
# config/initializers/custom_console_message.rb
if Rails.env.production?
Rails.application.console do
puts "Custom message here"
end
end
Now when starting the rails production console, the custom message will be printed. This code will not be executed when you start rails server.
Remove the if Rails.env.production? if you want this to run in all environments.

Rails is it possible?

Is it possible exec ruby code that is in a instance variable in a controller?
Example:
def something
#code = "redirect_to 'https://www.google.com/'"
exec(#code) // And then it would redirect.
end
DON'T DO THIS. Rails IS Ruby. In Ruby, you can execute any command inside a string using the eval method. And when you start really getting into it, there is class_eval.
#myvar = "puts 'SHOULD NOT HAVE DONE THIS!!'"
eval(#myvar) # SHOULD NOT HAVE DONE THIS!!
Keep safe.

In Ruby on Rails, "if defined? Product" doesn't work in script/runner mode?

If there is a simple script and to distinguish whether it is running by itself or being run inside the Rails app environment, I tried using
if defined? Product
# something
end
but it failed to be recognized even though Product is defined and can be used otherwise. Since then I tried using
if defined? RAILS_ENV
instead and it works well, but wonder why the defined? Product doesn't work?
This should work
if Product
# something
end
defined? ModelName returns nil for all my models.
Loading development environment (Rails 2.3.8)
>> defined? Post
=> nil
But then if I do this
>> Post; defined? Post
=> "constant"
Probably because nothing is loaded until you touch it. Hope this helps.
Edit: Ah ok well then, script/runner is a non-interactive form of script/console, I would think it loads the whole Rails app and runs from that context. If you need to identify wether the call was made from script/runner I can only think of passing a parameter to the function Model.long_running_method(:runner => true) and do your conditional check on that or if that is not convenient enough set a ENV constant ENV['something_runner']. And do the condition check on that instead.

Quickly debug helper methods in script\console

How would I quickly debug helper methods in script\console. I'm talking about making changes and then debugging, over and over again.
This is a lot easier with Model methods, since all I have to do is use
reload!
to test the updated code, whereas to test a helper method, I have to do something like this
foo = ActionView::Base.new
foo.extend YourHelperModule
each time to I want to test a change.
What does reload! do? and can I modify it to add the above lines of code?
I don't think you can do that without hacking Rails. However, there's a workaround - debugging helper method in rails debugger:
1) gem install ruby-debug
2) ruby script/server --debugger
3) place <% debugger %> into some view and open that page in browser
4) server window "turns into" console, where you can debug helper methods
5) 'return' command ends the debugging
If you modify the helper method and run the debugger again, you will get recent version of the method.
More info about debugger is here: http://railscasts.com/episodes/54-debugging-with-ruby-debug
I would suggest not using script console and writing tests in either Test::Unit or rspec instead. Google should get you pointed in the right direction there is a ton of information out there.
If you're doing something "again and again" then you should be automating it. Assuming you know what your helper function should do then as mentioned elsewhere you should be able to write a test (or tests) for it.
Here's a sample that tests application_helper. It lives in my test/unit directory:
require 'test_helper'
class ApplicationHelperTest < ActiveSupport::TestCase
include ApplicationHelper
test "number_as_pct shows 2dp as default" do
assert_equal "1.10%", number_as_pct(0.011)
end
test "number_as_pct shows more dp when required" do
assert_equal "1.1000%", number_as_pct(0.011, :precision => 4)
end
end

Resources