I'm trying to parse HTTP request headers in Test::Unit, but to no avail. I'm writing a functional test for a controller like so:
test "create a shopify order" do
get :order, PARAMS, {HEADER1 => VAL, HEADER2 => VAL}
assert_response :success # Make sure this returns 200, first off
...
end
Normally, I would read the headers like, request.headers[HEADER1], but this returns nil in Test::Unit. request isn't defined.
How do I actually grab the value of the headers I set in the above request? And how do I assign them to request? My app pulls from webservices, and I need to test the values that are passed through in headers, so I don't want to change my app code. I just need to simulate what those requests are like in Test::Unit.
Thanks!
Knowing what test quite you're using certainly helps (thanks Jesse). I found that I'd been looking at the doc for integration tests, not functional tests, and that setting headers works differently in functional tests:
http://twobitlabs.com/2010/09/setting-request-headers-in-rails-functional-tests/
So I wasn't setting the headers I thought I was. They were being read just fine--just not set.
Related
I am new to TDD and really enjoy it. I am using RSpec.
I am trying to learn to write good request specs (in general) and can find very little written on how to test the index method.
I have found this article: https://medium.com/#lcriswell/rails-api-request-specs-with-rspec-effeac468c4e, but I am not interested in testing an API, but an application with views.
What should I include on my index request tests and why?
The first spec in the article is great, you can use it in testing a regular controller for responses.
If you are using any sort of authorization(e.g cancancan), you can test the same request for multiple types of users and check if you get a redirect or a success(you might have to mock the sign-in).
For testing the views that are being rendered, you can try this:
it { is_expected.to render_template(:index) }
If your action assigns instance variables, you can test out that the variable is a certain value like so:
expect(assigns(:foo)).to be true
If your action responds to different formats(HTML, json, ...), you can write different contexts for each of the formats, each time by changing the request(hint: for JS in your specs submit your request like so: get :index, xhr: true)
Scenario:
We use capybara integration tests to test that our frontend plumbing (javascript) is connected properly.
Sometimes all we need to validate the test is:
has content rendered properly on the page
has the js called the correct url open interaction
Problem:
Item 1 above is easy. However, with item 2 I can't seem to find an easy way to say:
Assert that url was called from js in browser.
Example:
it "should call coorect url with correct query string" do
visit widgets_path
# THIS IS WHAT I NEED TO KNOW
expect(something).to receive(:some_method).with(url: "my/test/url", params: {per_page: 2})
# In other words, I don't want the controller action to run. I don't care about the result since the controller is being tested elsewhere.
# I just need to know that the correct URL was called with the correct params.
within 'ul.pagination' do
click_on '2'
end
end
I've tried mocking the controller action, but there's no way to inspect the params. Or is there? Without inspecting the params, how can I know if the correct stuff was sent? All I know it's the correct route, which isn't enough.
If I could inspect the params then this would be solved... but otherwise?
If you are looking for the Rails solution, here it is! Tested with Rails 5.1.3.
1) Create a request params matcher spec/support/matchers/request_with_params.rb
RSpec::Matchers.define :request_with_params do |params|
match { |request| request.params.symbolize_keys.slice(*params.keys) == params }
end
2) Create a helper method for your acceptance tests (you can use some logics to pass symbol instead of class UsersController -> :users if needed)
def expect_request(controller, action, params = {})
expect_any_instance_of(ActionDispatch::Routing::RouteSet::Dispatcher)
.to receive(:dispatch)
.with(controller, action.to_s, request_with_params(params), anything)
end
end
3) Use it!
expect_request(UsersController, :index)
or with params
expect_request(UsersController, :show, { id: 1 })
OR
4) There is another way in using https://github.com/oesmith/puffing-billy Check this gem for intercepting requests sent by your browser. But it can be an overkill if you need to mock only certain requests to your backend app.
Capybara integration tests intentionally don't support that. They are end-to-end blackbox tests, shouldn't generally be mocked, and really only support checking for things visible to the user in the browser. In your example case that would mean expecting on whatever visible change is caused by the JS call to the specific URL. Something like
expect(page).to have_css('div.widget', count: 2)
Short question
I need to post JSON in feature tests, something like in my controller tests:
post '/orders.json', params.to_json, format: :json
But I need to do it in feature tests, and page.driver.post only posts form data. How do I post JSON in Capybara?
Long Explanation
I have a (non-Rails) app (let's call it the planet) that posts JSON to my rails app (call it a star) to create a record, and then forwards the user to the url for the show action.
I'm creating a feature spec, but since the first interaction isn't part of the Rails, app, I need to mock it using JSON.
I've been using this:
page.driver.post '/orders.json', params.to_json
But this seems to post as a form, whereas my planet application posts JSON. This leads to some really funky parameter problems, where parsing JSON gives me different params from form-data.
How do I post JSON in Capybara?
TL;DR - you don't
Capybara is designed to emulate a user for feature tests. Hence why the post method is driver specific (page.driver.xxx) and really isn't intended for use directly by tests. A user can't just submit a POST without a page to submit it from. Therefore, if you do actually need to test this via feature tests, the best solution is to create a small test app that provides a page you can have Capybara visit which will automatically (or on button click, etc) have the browser make the AJAX post to the app under test and handle the response.
So, turns out that it just isn't possible with Capybara. See Thomas Walpole's answer for more details.
As a workaround, I used httparty:
require 'httparty'
RSpec.feature 'Checkouts', type: :feature do
include HTTParty
base_uri 'http://localhost:3000'
private
def checkout_with(cart)
post orders_path(format: :json).to_s,
body: cart.to_json,
headers: { 'Content-Type' => 'application/json' }
end
end
I am working on an app and up to this point I have been testing just stuff like authentication and request response codes. but it seems like a good idea to test the structure of the payload. ie. if there is embedded resources or sidloaded resources. how do you guys test this. here is a sample of some of the testing I am doing. I am using active model serializers. but seems like a bit of cruft to organize.
describe '#index' do
it 'should return an array of email templates' do
template = EmailTemplate.new(name: 'new email template')
EmailTemplate.stub(:all).and_return([template])
get :index
payload = {:email_templates => [JSON.parse(response.body)["email_templates"][0].symbolize_keys]}
template_as_json_payload = {:email_templates => [ActiveModel::SerializableResource.new(template).as_json[:email_template] ]}
expect(payload).to eq(template_as_json_payload)
end
end
I'm fond of defining a schema for JSON responses and validating that any response seen in a test conforms to it. That alone does not guarantee that the values of the response are correct but it does tell you that the structure of the response matched your expectations.
Those schemas then become part of the documentation of the API which client implementations can reference. By using the schema in tests I get more confidence that the API documentation is not going to fall out of sync with the implementation. Making schema changes in order to get a passing test is also a good prompt for me to consider if a change is safe for existing API clients or if I need to release a new API version.
The folks at Thoughtbot have a nice example of validating schemas using rspec: https://robots.thoughtbot.com/validating-json-schemas-with-an-rspec-matcher
This is one way to do it:
body = JSON.parse(response.body)
assert_equal(body.keys, ["id", "author"])
assert_equal(body["author"].keys, ["id", "name"])
But you should checkout the link that Jonah shared, it's worth reading.
I'm sending a POST request in a Rails functional test like this:
post :create, collection: { name: 'New Collection' }
collection gets sent as JSON-encoded form data, as expected.
What I can't figure out is how to add a query to the URL. The documentation says that I can access the request object and modify it before it gets sent. So I tried this:
#request.GET[:api_key] = 'my key'
post :create, collection: { name: 'New Collection' }
But, :api_key never appears in the request.GET hash on the server. (It does when I send it though another HTTP client, though.)
A little background first to clarify things: although a request cannot be both GET and POST at the same time, there is nothing stopping you from using both the query string and body form data when using POST. You can even have a POST with all parameters in the query string and an empty body, though this sounds quite unusual.
Rails supports this scenario and indeed you can easily send a form using a POST request and still have query in the form's action. The query will be accessible with request.GET hash (which is an alias of query_string), while the POST body params with the request.POST hash (an alias of request_parameters). The params hash is actually constructed from the combined GET and POST hashes.
However, from my research it seems that Rails does not support passing query string in POST requests in functional controller tests. Although I could not find anything regarding this in any documentation or among known issues on github, the source code is quite clear. In the following text, I'm assuming that you use Rails 4.
Why it does not work
The problem with functional controller tests is that they don't use real requests / responses but they simulate the HTTP handshake: the request is mocked up, its parameters filled in appropriate places and the given controller action is simply called as a normal ruby method. All of this is done in the action_controller/test_case classes.
As it turns out, this simulation is not working in your particular case, due to two reasons:
The parameters passed in when running the test are always handed over either to the request_parameters, i.e. the request.POST hash when using a post request or to the query_string (i.e. request.GET) for get test requests. There is no way for both of these hashes to be set during a single test run.
This actually makes some sense as the get, post, etc. helpers in functional tests accept only a single hash of params so the internal test code cannot know how to separate them into the two hashes.
It is true that one can set up the request before running the test using the #request variable, but only to a certain extent, you can set headers, for example. But you cannot set internal attributes of the request, because they are recycled during the test run. The recycling is done here and it resets all internal variables of the request object and the underlying rack request object. So if you try to set up the request GET parameters like this #request.GET[:api_key] = 'my key', it won't have any effect as the internal variables representing this hash will get wiped during recycling.
Solutions / workarounds
Give up functional testing and choose integration tests instead. Integration tests allow to set the rack environment variables separately from the main parameters. The following integration test passes the QUERY_STRING rack env variable besides the normal post body params and should work flawlessly:
class CollectionsTest < ActionDispatch::IntegrationTest
test 'foo' do
post collections_path, { collection: { name: 'New Collection' } },
{ "QUERY_STRING" => "api_key=my_api_key" }
# this proves that the parameters are recognized separately in the controller
# (you can test this in you controller as well as here in the test):
puts request.POST.inspect
# => {"collection"=>{"name"=>"New Collection"}}
puts request.GET.inspect
# => {"api_key"=>"my_api_key"}
end
end
You can still use most of the features from functional tests in your integration tests. E.g. you can test for assigned instance variables in the controller with the assigns hash.
The transition argument is supported also by the fact that Rails 5 will deprecate functional controller tests in favor of integration testing and since Rails 5.1 these functional tests support will be moved out to a separate gem.
Try Rails 5: although functional tests will be deprecated, its source code seems to have been heavily rewritten in the rails master and e.g. recycling of the request is not used any more. So you might give it a try and try to set the internal variables of the request during test setup. I have not tested it though.
Of course, you can always try to monkey-patch the functional test so that it supports separate params for the query_string and request_parameters hashes to be defined in tests.
I'd go the integration tests route :).
I assume that the controller is named CollectionsController, and its route to create action is /collections (if not, you just have to adapt the example bellow)
And I also assume you are in a request spec
This should work:
post '/collections?api_key=my_key', collection: { name: 'New Collection' }
The 2nd argument to post is a hash of all the params you'll receive in the controller. Just do this:
post :create, collection: { name: 'New Collection' }, more_params: 'stuff', and_so_on: 'things'
Those params will be available in the controller:
params[:and_so_on] == 'things'
You want to send a POST request:
I'm sending a POST request in a Rails functional test like this:
But you want to retrieve data from a GET request:
But, :api_key never appears in the request.GET hash on the server.
A request cannot be GET and POST at the same time, if you are sending a POST request and pass parameters in the query string then you would have those parameter values available on a POST request, GET just won't have anything.
Then:
#request.GET[:api_key] = 'my key'
post :create, collection: { name: 'New Collection' }
You are modifying the GET values on the request, but then you actually send a POST request which means that when the post method gets called and the request is sent to the server only what you sent on the POST will be available. Just send the api key bundled with the POST request (could be inside the collection hash for that matter)
This is also a problem when testing POST actions with RSpec (v3.4).
A workaround is to mock the return value of request.GET or request.query_string methods.
it "should recognise a query parameter in post action" do
allow(subject.request).to receive(:query_string).and_return("api_key=my%20key")
#params = {collection: { name: 'New Collection' }}
expect(subject.request.query_string).to eq "api_key=my%20key"
post :create, #params
end