Rspec - Set format json for request
If I want to test API POST /users, I usually setup rspec code like that:
context "when we create user success" do
let(:params) do
{
name: "User A",
age: 28
}
end
before { post :create, params: params }
it "should create new user" do
# expect come here
end
endIt’s OK, and I could save user to DB.
However, we have problem. If you want to validate params[:age] > 20, in controller, when I call:
params[:age] # => "28", instead of 28cause Rspec auto convert number to string when it pass params to the controller.
So, to fix this, you need to tell RSpec that you will use format: :json, so it
will not treat integer varialbes as string.
Solution
# Solution 1
before { post :create, params: params, format: :json }
# Solution 2
before { post :create, params: params, as: :json }
# Solution 3
before do
request.headers["CONTENT_TYPE"] = "application/json"
endReferences: