Тестирование сообщения rspec с помощью Rails JSONAPI::Serializer

Я использую гем jsonapi-serializers, и у меня возникли проблемы с выяснением того, как протестировать почтовый запрос с помощью rspec и полезной нагрузки json. Я знаю, что это работает, потому что я могу использовать postman и отправлять json, и он успешно создает новый объект, но я не уверен, почему я не могу заставить работать тест rspec.

Вот метод контроллера API:

def create
  @sections = @survey.sections.all
  if @sections.save
    render json: serialize_model(@section), status: :created
  else
    render json: @section.errors, status: :unproccessable_entity
  end
end

serialize_model просто помощник для JSONAPI::Serializer.serialize

Вот мои текущие тесты rspec для этого контроллера:

describe 'POST #create' do
  before :each do
    @section_params = { section: { title: 'Section 1', position: 'top', instructions: 'fill it out' } }
    post '/surveys/1/sections', @section_params.to_json, format: :json
  end

  it 'responds successfully with an HTTP 201 status code' do
    expect(response).to be_success
    expect(response).to have_http_status(201)
  end
end

Я пробовал несколько разных вещей и не могу понять, как это исправить. Если я опубликую этот URL-адрес с Postman и этой точной полезной нагрузкой json, он успешно создаст новый раздел.

Тесты запроса на получение работают нормально, я просто не уверен, как обрабатывать данные запроса json с помощью rspec и jsonapi-serializer.


person mikeLspohn    schedule 26.01.2016    source источник


Ответы (1)


Попробуй это. Замените YourApiController на то, что вы назвали своим

describe YourApiController, type: :controller do
  context "#create" do
    it 'responds successfully with an HTTP 201 status code' do
      params = { section: { title: 'Section 1', position: 'top', instructions: 'fill it out' } }
      survey = double(:survey, sections: [])
      sections = double(:sections)
      section = double(:section)
      expect(survey).to receive(:sections).and_return(sections)
      expect(sections).to receive(:all).and_return(sections)
      expect(sections).to receive(:save).and_return(true)
      expect(controller).to receive(:serialize_model).with(section)
      post :create, params, format: :json
      expect(response).to be_success
      expect(response).to have_http_status(201)
      expect(assigns(:sections)).to eq sections
    end
  end
end
person MilesStanfield    schedule 27.01.2016
comment
Спасибо, это помогло! - person mikeLspohn; 28.01.2016