Test Rails nested form POST via terminal - ruby-on-rails

I have created nested form and want to test it from terminal. How can I Make POST request that creates 2 records - one for parent and one for child - at once?

Pry can help. This is not "testing" but more "debugging" in terminal.
gem 'pry'
bundle install
and in the beginning of your action accepting post request, let's say create;
def create
binding.pry
...
end
Browser will not respond but you will get what you want in your terminal.
See this railscast for more info.

HTTP-wise, nested forms are no different than regular forms. Rails uses the naming of the fields to separate parent data from child data. Use your browser's inspector to inspect the HTTP request sent when you fill out the form manually. From there, you can see the name of all the fields used. Then, in terminal, you can typically do something like this:
curl --data "parent[foo]=1&child[bar]=2" http://myapp.dev/parent/create
Just replace the parent[foo] and similar with what you find in the inspector, and it should all work. Tail the dev log if you want to see potential errors in the request.

How about to use rspec testing framework?

Related

Rails load seed - feedback

I have a admin page on my site which allows me to load seeds by clicking a link.
it just calls:
Rails.application.load_seed
Problem is, there is no feedback that this is happening - I would like to see the seed output somehow on the page (the same as if ran in the command line).
Is there a way to do this when the link is clicked?
If you care about the page reloading, you could use jquery to do an ajax post request to a route, run the script (it doesn't need to be in the seed file--you could run it in the controller action you create) you're running to add data, and then in your success callback append the results.
If by 'output' you mean messages printed to standard output (e.g. using puts in the seeds file), you might grab the output in the controller using the code from this SO answer):
# controller:
#output = with_captured_stdout { Rails.application.load_seed }
But this will only display after the load finishes, you won't get any info during the process. If you require that, I think you'd need some streaming techniques.

Outputting HTTP request/response data with RSpec

I have a rails project that serves a JSON API with tests written in RSpec. Often when running specs (request specs, specifically), I’m interested in seeing some details about the HTTP request/response...i.e. the request URL, request body, and response body, ideally JSON pretty-formatted for readability. This isn't for the purposes of documentation but rather as part of the development / debugging process.
I have a helper method I wrote which does this...you just drop a method call into your spec and it prints this stuff out.
But, seems like it would be better if there was a switch that’s part of the running specs. RSpec has custom formatters which I thought might be the right direction, but in trying to build one, I can't figure out how to get access to the request/response objects like you can from inside of your spec.
How can I access the request/response objects in my custom RSpec formatter? Or, perhaps another way to approach the problem?
Here's an approach:
Assuming a rails project, in spec_helper.rb, define a global "after" hook like so:
config.after(:each) do #runs after each example
if ENV['PRINTHTTP']
#use request/response objects here, e.g. puts response.status
end
end
Then, you can conditionally enable by adding the environmental variable on the command-line:
$ PRINTHTTP=1 rspec

How to get the value of a Controller variable in rails console

I set a variable inside a Controller and I'm trying to just do something as simple as read that variable in the rails console.
I thought about just doing #test in the console which is the name of the variable. but it shows as >null. When I do puts under where I set the variable it traces out the correct value in my terminal window.
Any ideas what I need to do to get to this variable via the console.
I tried putting the name of the controller first and then .variable but that threw an error
I can see what's inside my models by just using the model name and some attributes like .first and .last
You'd have to instantiate the controller and provide a public accessor to get the value in rails console.
If you're trying to debug something, I recommend you check out Pry. It's a Ruby debugging REPL. Do a require 'pry' in your controller, and put binding.pry somewhere in an action, when you execute that controller method--either interactively in a browser, or via a functional test (I recommend the latter)--it will open the Pry REPL and #test will be in scope there.
Check out this Railscast for some help using it.
Alternately, just rely on good unit or functional testing. Write a test around the method and add an assertion on assigns(:#test) to compare the value to your expectation. Check out the RSpec controller spec documentation.

How to get the fully qualified name of method in Ruby?

Let's say that I've got a method available in my workspace in Ruby. Is there a command I can use that will recover the fully qualified name of the method?
I'm looking for something similar to the which function in Matlab, that returns an unambiguous name for any argument it's given.
I ask because I'm writing a test in Cucumber that needs to send particular GET and POST requests. I have both get and post methods in my workspace, but I didn't import them myself and so I don't know where they came from. I want to look at the documentation for these methods. In order to find the documentation, I need to know what module they're defined in. I'm trying to get the fully qualified names in order to figure out which module they're from.
I figured it out. Andrew Marshall left a comment that pointed me in the right direction.
First I installed pry, by including it in my gemfile and running bundle install.
Then I inserted binding.pry into my test code. This dropped me into a pry session when I ran my tests.
In the pry session I typed the ls command, which listed all the variables in my context. I found get and post under Rack::Test::Methods#methods.
Rack::Test::Methods#methods: _current_session_names authorize basic_authorize build_rack_mock_session build_rack_test_session clear_cookies current_session delete digest_authorize follow_redirect! get head header last_request last_response options post put rack_mock_session rack_test_session request set_cookie with_session
So, one way to find out the FQN of a method in your workspace is to run Pry's ls command, and then examine the output.

in Ruby on Rails 2.3.2, how to print out params during a create action?

there is a scaffold created Story... and in the create action, there is
#story = Story.new(params[:story])
i was curious as to what is in params... so i want to dump out params... but there is no view associated with the create action... is there a way to dump out its content? is there a way to dump out the POST variables in of my code too? (to see what's going on in the lower level)
The easiest thing to do is just dump params out to the log:
Rails.logger.info("PARAMS: #{params.inspect}")
If you're in development mode, just look in your development.log and that line will be there.
The params scope is a combination of URL/FORM (GET/POST) fields, and it will be printed out in the log as part of the normal output processing, so you might not need your own dumping of it - any development or production log contains the params dump at the top of the log line, e.g.
Processing Clients::ClientsController#show (for x.x.x. at 2009-05-24 00:34:26) [GET]
Parameters: {"id"=>"303", "user_id"=>"2"}
Now I know Rails more, you can also simply use a
p params
in your code and look at the console's output (the log shown on the console)
If you're on a Mac, Spike is a great little app the analyses log files and will let you inspect params for requests, amongst other things.
Using Fiddler on Windows, it is shown
the HTTP line #1 is:
POST /stories HTTP/1.1
this is the POST content:
authenticity_token=62iw%2BrsxlCFsbnxsS7FXKRn6CcvJfjottrsBPlM5lZo%3D&story%5Bname%5D=Google+Main+Site&story%5Blink%5D=www.google.com&commit=Create
listed in a table:
authenticity_token 62iw+rsxlCFsbnxsS7FXKRn6CcvJfjottrsBPlM5lZo=
story[name] Google Main Site
story[link] www.google.com
commit Create
and the server log is:
Parameters: {"commit"=>"Create", "story"=>{"name"=>"Google Main Site", "link"=>"www.google.com"}, "authenticity_token"=>"62iw+rsxlCFsbnxsS7FXKRn6CcvJfjottrsBPlM5lZo="}
You don't need to anything except look in your logs (they live in /log). Unless you're fiddling with something, the logging of parameters is turned on by default in all logs.
Processing PostsController#create (for 127.0.0.1 at 2009-05-24 13:03:24) [POST]
Parameters: {"commit"=>"Create", "authenticity_token"=>"2G6BKOs8xNAaXiToVf4r1ko8QZzP9QAomi2PHVQC5Oc=", "story"=>{"something"=>"asdfafd"}}
Parameters lists all parameters, and the hash following "story" is the equivalent of params[:story] (everything comes to the server as strings, and Rails turns it into a HashWithIndifferentAccess so that you can access it with a symbol).
If you're on a *NIX system (including OS X) open a new terminal window/tab and type the following command:
tail -f log/development.log
You'll get a constant stream of requests coming in -- including params -- and the resulting DB actions. Invaluable for development/debugging, IMO.

Resources