I currently have the following situation:
ChallengeRequestsController #new - creates a ChallengeRequest along with another model needing a recpient_id.
def create
#challenge_request = ChallengeRequest.new(challenge_params)
recipient = User.find(params.require(:recipient_id))
# Rest of method redacted.
end
def challenge_params
params.require(:challenge_request).permit(:action)
end
With this controller, I have an RSpec test as follows:
RSpec.describe ChallengeRequestsController, type: :controller do
describe "POST #create" do
context "with valid challenge request" do
let(:valid_challenge_request) { build(:challenge_request) }
context "with non-exisistent recpient id" do
it "throws an error" do
expect{
post :create, :params => {
:challenge_request => {
:challenge_request => valid_challenge_request
},
:recipient_id => 10000
}
}.to raise_error ActiveRecord::RecordNotFound
end
end
end
end
end
Just for reference, here's the Factory:
FactoryGirl.define do
factory :challenge_request do
action { Faker::LeagueOfLegends.champion }
end
end
All of this code works and the test passes, my question is how can I refactor this in a way that I don't need to use the ugly nesting in the request?
:challenge_request => {
:challenge_request => valid_challenge_request
}
When posting the request without this nesting:
post :create, :params => {
:challenge_request => valid_challenge_request,
:recipient_id => 10000
}
The challenge_request is empty when the ChallengeRequestController receives the request.
It would probably work if you change your valid_challenge_request to be a hash of attributes instead of the model itself.
let(:valid_challenge_request) { FactoryBot.attributes_for(:challenge_request) }
You're trying to send along an instance of a model as a parameter to a controller, and something is doing something (I can't find what's doing what to the model) to try and coerce it into something that a browser might send the controller. That conversion is turning the model into an empty string, which is not present or the value false and thus causes the require to throw the ParameterMissing
rails 5.0.0.1
rspec 3.5
I have inherited a code base. I am busy writing integration tests to tie down the app functionality before I consider refactoring.
I have the following lines in a controller concern before_action. It seems to read the request body. The json value here is used to extract an identifier used to authenticate the request.
request.body.rewind
body = request.body.read
json = JSON.parse(body) unless body.empty?
I need to test that the authentication happens correctly.
How can I set the request.body for a GET request spec?
I think you should be able to do this via the request env RAW_POST_DATA
get root_path, {}, 'RAW_POST_DATA' => 'raw json string'
request.raw_post # "raw json string"
See:
How to send raw post data in a Rails functional test?
https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec
#rails_post_5
require "rails_helper"
RSpec.describe "Widget management", :type => :request do
it "creates a Widget and redirects to the Widget's page" do
headers = { "CONTENT_TYPE" => "application/json" }
post "/widgets", :params => '{ "widget": { "name":"My Widget" } }', :headers => headers
expect(response).to redirect_to(assigns(:widget))
end
end
or just
post "/widgets", params: '{ "widget": { "name":"My Widget" } }'
Controller: payments_controller.rb
class PaymentsController < ApplicationController
# This is needed to have Postman work
skip_before_action :verify_authenticity_token
rescue_from ActiveRecord::RecordNotFound do |exception|
render json: 'not_found', status: :not_found
def create
new_payment = Payment.new(new_params)
current_loan = Loan.find(new_params[:loan_id])
if Payment.valid?(new_payment, current_loan)
Payment.received(new_payment, current_loan)
current_loan.save
new_payment.save
redirect_to '/loans'
else
raise 'Amount entered is above the remaining balance'
end
end
end
This method works when I test it in Postman. However, I can't seem to write a test for it that passes. I currently have:
payments_controller_spec.rb
require 'rails_helper'
RSpec.describe PaymentsController, type: :controller do
describe "#create", :type => :request do
let!(:loan) {Loan.create!(id: 1, funded_amount: 500.0)}
params = '{"payment":{"amount":400, "loan_id":2}}'
it 'creates and saves a payment while saving the associated fund_amount of the loan' do
post "/payments", params.to_json, {'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json'}
expect(loan.funded_amount).to eql(600.0)
end
end
end
The error is:
Failure/Error: post "/payments", params.to_json, {'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json'}
ActionController::ParameterMissing:
param is missing or the value is empty: payment
Valid parameters (that work with Postman) are:
{"payment":{"amount":400,"loan_id":2}}
Any help would be appreciated!
*** UPDATE ****
After messing around with this for a while, I finally got it to work with this:
describe "#create", :type => :request do
let!(:loan) {Loan.create!(id: 1, funded_amount: 500.0)}
it 'creates and saves a payment while saving the associated fund_amount of the loan' do
json = { :format => 'json', :payment => { :amount => 200.0, :loan_id => 1 } }
post '/payments', json
loan.reload
expect(loan.funded_amount).to eql(300.0)
end
end
You can pass in your params like this.
it 'creates and saves a payment while saving the associated fund_amount of the loan' do
post "/payments", payment: { amount: 400, loan_id: 1 }, {'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json'}
expect(loan.funded_amount).to eql(600.0)
end
I'm currently building a JSON API powered by Rails/rails-api. I have a route which accepts JSON send via a PATCH request and a before filter which needs access to the raw request/JSON.
For testing purposes I added following before filter to show my problem:
before_filter do
puts "Raw Post: #{request.raw_post.inspect}"
puts "Params: #{params.inspect}"
end
The following curl request works as intended:
curl -X PATCH -H "Content-Type: application/json" -d '{"key":"value"}' http://localhost:3000/update
# Raw Post: "{\"key\":\"value\"}"
# Params: {"key"=>"value", "action"=>"update", "controller"=>"posts"}
However I fail testing this method, none of the following calls do work:
Params included, but not as JSON transferred
test 'passing hash' do
patch :update, { key: "value" }
end
# Raw Post: "key=value"
# Params: {"key"=>"value", "controller"=>"posts", "action"=>"update"}
Params included, but again not as JSON transferred
test 'passing hash, setting the format' do
patch :update, { key: "value" }, format: :json
end
# Raw Post: "key=value"
# Params: {"key"=>"value", "controller"=>"posts", "action"=>"update", "format"=>"json"}
JSON format, but not included in params
test 'passing JSON' do
patch :update, { key: "value" }.to_json
end
# Raw Post: "{\"key\":\"value\"}"
# Params: {"controller"=>"posts", "action"=>"update"}
JSON format, but not included in params
test 'passing JSON, setting format' do
patch :update, { key: "value" }.to_json, format: :json
end
# Raw Post: "{\"key\":\"value\"}"
# Params: {"format"=>"json", "controller"=>"posts", "action"=>"update"}
This list is even longer, I just wanted to show you my problem. I tested setting both the Accept and Content-Type headers to application/json too, nothing seems to help. Am I doing something wrong, or is this a bug in Rails' functional tests?
This is a bug, reported by same author of this question. It is not likely to be fixed until Rails 5, or so it seems by looking at the milestone it has been assigned to.
If you land here, like me, after some hours dealing with this issue unknowing that it is really a bug, maybe you want to know that you can do that in an Integration test:
$ rails g integration_test my_integration_test
require 'test_helper'
class MyIntegrationTestTest < ActionDispatch::IntegrationTest
setup do
#owner = Owner.create(name: 'My name')
#json = { name: 'name', value: 'My new name' }.to_json
end
test "update owner passing json" do
patch "/owners/#{#owner.id}",
#json,
{ 'Accept' => Mime::JSON, 'Content-Type' => Mime::JSON.to_s}
assert_response :success
assert_equal 'application/json', response.headers['Content-Type']
assert_not_nil assigns :owner
assert_equal 'My new name', assigns(:owner).name
end
end
I am doing functional tests for my controllers with Rspec. I have set my default response format in my router to JSON, so every request without a suffix will return JSON.
Now in rspec, i get an error (406) when i try
get :index
I need to do
get :index, :format => :json
Now because i am primarily supporting JSON with my API, it is very redundant having to specify the JSON format for every request.
Can i somehow set it to default for all my GET requests? (or all requests)
before :each do
request.env["HTTP_ACCEPT"] = 'application/json'
end
Put this in spec/support:
require 'active_support/concern'
module DefaultParams
extend ActiveSupport::Concern
def process_with_default_params(action, parameters, session, flash, method)
process_without_default_params(action, default_params.merge(parameters || {}), session, flash, method)
end
included do
let(:default_params) { {} }
alias_method_chain :process, :default_params
end
end
RSpec.configure do |config|
config.include(DefaultParams, :type => :controller)
end
And then simply override default_params:
describe FooController do
let(:default_params) { {format: :json} }
...
end
The following works for me with rspec 3:
before :each do
request.headers["accept"] = 'application/json'
end
This sets HTTP_ACCEPT.
Here is a solution that
works for request specs,
works with Rails 5, and
does not involve private API of Rails (like process).
Here's the RSpec configuration:
module DefaultFormat
extend ActiveSupport::Concern
included do
let(:default_format) { 'application/json' }
prepend RequestHelpersCustomized
end
module RequestHelpersCustomized
l = lambda do |path, **kwarg|
kwarg[:headers] = {accept: default_format}.merge(kwarg[:headers] || {})
super(path, **kwarg)
end
%w(get post patch put delete).each do |method|
define_method(method, l)
end
end
end
RSpec.configure do |config|
config.include DefaultFormat, type: :request
end
Verified with
describe 'the response format', type: :request do
it 'can be overridden in request' do
get some_path, headers: {accept: 'text/plain'}
expect(response.content_type).to eq('text/plain')
end
context 'with default format set as HTML' do
let(:default_format) { 'text/html' }
it 'is HTML in the context' do
get some_path
expect(response.content_type).to eq('text/html')
end
end
end
FWIW, The RSpec configuration can be placed:
Directly in spec/spec_helper.rb. This is not suggested; the file will be loaded even when testing library methods in lib/.
Directly in spec/rails_helper.rb.
(my favorite) In spec/support/default_format.rb, and be loaded explicitly in spec/rails_helper.rb with
require 'support/default_format'
In spec/support, and be loaded by
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
which loads all the files in spec/support.
This solution is inspired by knoopx's answer. His solution doesn't work for request specs, and alias_method_chain has been deprecated in favor of Module#prepend.
In RSpec 3, you need make JSON tests be request specs in order to have the views render. Here is what I use:
# spec/requests/companies_spec.rb
require 'rails_helper'
RSpec.describe "Companies", :type => :request do
let(:valid_session) { {} }
describe "JSON" do
it "serves multiple companies as JSON" do
FactoryGirl.create_list(:company, 3)
get 'companies', { :format => :json }, valid_session
expect(response.status).to be(200)
expect(JSON.parse(response.body).length).to eq(3)
end
it "serves JSON with correct name field" do
company = FactoryGirl.create(:company, name: "Jane Doe")
get 'companies/' + company.to_param, { :format => :json }, valid_session
expect(response.status).to be(200)
expect(JSON.parse(response.body)['name']).to eq("Jane Doe")
end
end
end
As for setting the format on all tests, I like the approach from this other answer: https://stackoverflow.com/a/14623960/1935918
Perhaps you could add the first answer into spec/spec_helper or spec/rails_helper with this:
config.before(:each) do
request.env["HTTP_ACCEPT"] = 'application/json' if defined? request
end
if in model test (or any not exist request methods context), this code just ignore.
it worked with rspec 3.1.7 and rails 4.1.0
it should be worked with all rails 4 version generally speaking.
Running Rails 5 and Rspec 3.5 I had to set the headers to accomplish this.
post '/users', {'body' => 'params'}, {'ACCEPT' => 'application/json'}
Thi matches what the example in the docs looks like:
require "rails_helper"
RSpec.describe "Widget management", :type => :request do
it "creates a Widget" do
headers = {
"ACCEPT" => "application/json", # This is what Rails 4 accepts
"HTTP_ACCEPT" => "application/json" # This is what Rails 3 accepts
}
post "/widgets", { :widget => {:name => "My Widget"} }, headers
expect(response.content_type).to eq("application/json")
expect(response).to have_http_status(:created)
end
end
Per the Rspec docs, the supported method is through the headers:
require "rails_helper"
RSpec.describe "Widget management", :type => :request do
it "creates a Widget" do
headers = {
"ACCEPT" => "application/json", # This is what Rails 4 and 5 accepts
"HTTP_ACCEPT" => "application/json", # This is what Rails 3 accepts
}
post "/widgets", :params => { :widget => {:name => "My Widget"} }, :headers => headers
expect(response.content_type).to eq("application/json")
expect(response).to have_http_status(:created)
end
end
For those folks who work with request tests the easiest way I found is to override #process method in ActionDispatch::Integration::Session and set default as parameter to :json like this:
module DefaultAsForProcess
def process(method, path, params: nil, headers: nil, env: nil, xhr: false, as: :json)
super
end
end
ActionDispatch::Integration::Session.prepend(DefaultAsForProcess)
Not sure if this will work for this specific case. But what I needed in particular was to be able to pass a params hash to the post method. Most solutions seem to be for rspec 3 and up, and mention adding a 3rd parameter like so:
post '/post_path', params: params_hash, :format => 'json'
(or similar, the :format => 'json' bit varies)
But none of those worked. The controller would receive a hash like: {params: => { ... }}, with the unwanted params: key.
What did work (with rails 3 and rspec 2) was:
post '/post_path', params_hash.merge({:format => 'json'})
Also check this related post, where I got the solution from: Using Rspec, how do I test the JSON format of my controller in Rails 3.0.11?
Why don't RSpec's methods, "get", "post", "put", "delete" work in a controller spec in a gem (or outside Rails)?
Based off this question, you could try redefining process() in ActionController::TestCase from https://github.com/rails/rails/blob/32395899d7c97f69b508b7d7f9b7711f28586679/actionpack/lib/action_controller/test_case.rb.
Here is my workaround though.
describe FooController do
let(:defaults) { {format: :json} }
context 'GET index' do
let(:params) { defaults }
before :each do
get :index, params
end
# ...
end
context 'POST create' do
let(:params) { defaults.merge({ name: 'bar' }) }
before :each do
post :create, params
end
# ...
end
end