【发布时间】:2018-08-08 20:44:24
【问题描述】:
所以我正在尝试测试发布请求以保存一些图书详细信息。响应以原始 JSON 的形式出现,因为它在客户端使用 formData 进行了字符串化。这样我就可以在控制器中适当地格式化响应。 我找不到任何明确的方法来发送原始 JSON 参数,因为 rails 会自动将这些参数强制为 HASH。有什么建议吗? 导轨 5.1.4 Rspec 3.7.2
books_spec.rb
# Test suite for POST /books
describe 'POST /books' do
# valid payload
let(:valid_attributes) do
# send stringify json payload
{
"title": "Learn Elm",
"description": "Some good",
"price": 10.20,
"released_on": Time.now,
"user_id": user.id,
"image": "example.jpg"
}.to_json
end
# no implicit conversion of ActiveSupport::HashWithIndifferentAccess into String
context 'when the request is valid' do
before { post '/books', params: valid_attributes, headers: headers }
it 'creates a books' do
expect(json['book']['title']).to eq('Learn Elm')
end
it 'returns status code 201' do
expect(response).to have_http_status(201)
end
end
context 'when the request is invalid' do
let(:valid_attributes) { { title: nil, description: nil }.to_json }
before { post '/books', params: valid_attributes, headers: headers }
it 'returns status code 422' do
expect(response).to have_http_status(422)
end
it 'returns a validation failure message' do
expect(response.body)
.to match(/Validation failed: Title can't be blank, Description can't be blank/)
end
end
end
books_controller.rb
# POST /books
def create
@book = current_user.books.create!(book_params)
render json: @book, status: :created
end
def book_params
binding.pry # request.params[:book] = HASH
parsed = JSON.parse(request.params[:book])
params = ActionController::Parameters.new(parsed)
params['image'] = request.params[:image]
params.permit(
:title,
:description,
:image,
:price,
:released_on,
:user
)
end
【问题讨论】:
标签: ruby-on-rails rspec rspec-rails