Testing controllers using RSpec with JSON parameters successfully passing

I'm currently working on creating a POST json request in an RSpec Controller test, where I need to pass params. Take a look at my code snippet below:

it 'returns access_token' do
    post :login, email: 'bla', password: 'bla1', format: :json

When I examine the data received in the controller's request.body.read, I notice that the params are passed as a string in this format: email=bla&password=bla1

This is not the JSON format I was expecting. However, when I make the same request using CURL:

curl -d '{"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c1e101d3c1e101d521f1311">[email protected]</a>" }' http://127.0.0.1:3000/users/login --header "Accept: application/json" --header "Content-Type: application/json"

The data retrieved from request.body.read now appears as valid JSON:

"{\"email\": \"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcded0ddfcded0dd92dfd3d1">[email protected]</a>\", \"password\": \"bla1\" }"

So my main question here is how can I achieve this format when passing params in RSpec tests?

Answer №1

submit "/items/#{@item.id}",
        variables: {
            specific_data: "5678",
        },
        with_content_type: :json

Answer №2

To include a header in your RSpec file, you can use the following code:

header "Content-Type", "application/json"
post :something

If you want to pass parameters, you can do so like this:

post :create, :object => { :email => email,
                           ...
                         }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a null pointer exception when using a post method, JSON, and AJAX

Implementing Server Side Logic @Path("/create") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}) public RequestStatus createData(String jsonData){ return ...

Utilizing Postgres, explore the effectiveness of substring indexing and matching on JSON string arrays

I am using PostgreSQL and have a table with a jsonb field defined as json JSONB NOT NULL. Within this jsonb field, I have an array of strings, such as: { "values": ["foo", "bar", "foobar"]} To search for rows that c ...

Receive JSON data with camel-case in a Web API 2.0 using a model in pascal-case style

My attempt to execute a PUT call on my Web API involves configuring the WebApiConfig.cs file to send data back to my Web project in camel case format. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesCont ...

Utilizing handpicked information in Angular: A beginner's guide

Being new to Angular and programming in general, I am currently navigating through the intricacies of Angular and could use some guidance on utilizing selected data. For instance, I would like to use a personnel number view image here and send it to the b ...

Sending a cURL POST request to a Node.js express server running on an NGINX server resulted in a 502 error response

I am attempting to send a POST request to one of my node API routes. Strangely, only one of them seems to be working properly. I'm not certain whether this is an issue with NGINX, Node.js, or a combination of both. I have double-checked everything and ...

Implementing communication between directive and controller in AngularJS by updating the changed value

Typically, the sequence of execution is controller ---> directive, isn't it? Here's a scenario I have: In the controller, we set the default value for placeholder: $scope.formsDropDown = { show: true, placeholder: 'Select a Form&ap ...

The issue of Rails time lagging by a day persists upon deployment on my server

When a user clicks on a day in my calendar, I pass a JavaScript time variable to my Rails controller using Ajax. Everything works perfectly when I test it locally, but once deployed on the server, the date appears to be one day behind the actual day click ...

How can I generate JSON format in Ruby?

I am facing issues generating the desired format for an API input. The required format is as follows: { "application" : "{\"attributes\":{\"type\":\"genesis__Applications__c\"},\"genesis__Days_Convention__c\":&b ...

Utilize Python to consolidate data from various API requests

I am currently developing an application that will need to interact with multiple external APIs to gather information and then present the results to a client. The client interacts with the application through a web interface, submitting queries to the ser ...

Retrieve JSON data from a PHP script to be used in an Angular scope

I am attempting to retrieve JSON data from a PHP file to use in an Angular controller. I have used json_encode(pg_fetch_assoc($result)); within the PHP file and when I check with console.log($scope.contents); in the Angular controller, the JSON data is ret ...

ExpressJs responds with an empty JSON object

During the validation of a mongoose schema within 'pre' of parallel middleware schema.pre('save', true, function (next, done) { if(...) { next(new Error('Some error message')); } next(); }); After returning an err ...

Using AngularJS to create a form and showcase JSON information

My code is below: PizzaStore.html: <!DOCTYPE html> <html ng-app="PizzaApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Delicious pizza for all!</title> ...

Embedding JSON data in a GSP page

My goal is to transfer JSON data to a GSP page and present it in a table format. The expected JSON structure: { "data": [ [ "Tiger Nixon", "System Architect", "Edinburgh" ] ]} I attempted to achieve this with the following co ...

Display the JSON data in a table by utilizing the ng-repeat directive in Angular

Below is the response that I have: Response : response: {"json": {"response": {"servicetype":"", "functiontype":"", "statuscode":"0", "statusmessage":"Success", "data":[{"graphtype":"piechart", "xlabel":"state", "ylabel":"count", "s1":"contact", "s2":" ...

Searching for specific information within a JSON file (across multiple lines)

Currently, I am working on extracting specific lines of data from a JSON file. It seems that using grep in this particular scenario might be the way to go, but I could use some guidance. Below is an example of the JSON data: [ 'vlans VLAN10 vlan-id 1 ...

Is it important to clean user input before displaying it on the screen while also permitting all characters

Currently, I have a JavaScript function that limits the characters accepted for user input in order to safely display it in the DOM. Now, I want to allow all characters while still encoding them to prevent any malicious scripts from executing. How can I a ...

Is there a specific method to access a JSON file with (js/node.js)?

Searching for a way to access user information stored in a JSON file using the fs module in node.js. Specifically looking to read only one user at a time. app.get("/1", function(req, res) { fs.readFile("users.json",function(data, err){res.write(data)}} W ...

Understanding the basics of Maven imports: troubleshooting class not found errors

After adding the following to my pom.xml: <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20170516</version> </dependency> The desired json classes, such as JSONArray, ...

Analyze items in two arrays using JavaScript and add any items that are missing

I am working on a JSON function that involves comparing objects in two different arrays, array1 and array2. The goal is to identify any missing items and either append them to array2 or create a new array called newArray1. Here is an example: const arra ...

Using rowspan to display JSON data in AngularJS

Unique Json data: [{ cityName: Seattle, population: 1000000, rank: 1 }, { cityName: Portland, population: 800000, rank: 2 }, { cityName: San Francisco, population: 900000, rank: 3 }, { cityName: Los Ange ...