[ruby-on-rails] RSpec을 사용하여 JSON 응답을 확인하는 방법은 무엇입니까?

컨트롤러에 다음 코드가 있습니다.

format.json { render :json => {
        :flashcard  => @flashcard,
        :lesson     => @lesson,
        :success    => true
} 

내 RSpec 컨트롤러 테스트에서 특정 시나리오가 성공 json 응답을 수신하는지 확인하여 다음 줄을 가지고 싶습니다.

controller.should_receive(:render).with(hash_including(:success => true))

테스트를 실행할 때 다음 오류가 발생합니다.

Failure/Error: controller.should_receive(:render).with(hash_including(:success => false))
 (#<AnnoController:0x00000002de0560>).render(hash_including(:success=>false))
     expected: 1 time
     received: 0 times

응답을 잘못 확인하고 있습니까?



답변

응답 오브젝트를 검사하고 예상 값을 포함하는지 검증 할 수 있습니다.

@expected = {
        :flashcard  => @flashcard,
        :lesson     => @lesson,
        :success    => true
}.to_json
get :action # replace with action name / params as necessary
response.body.should == @expected

편집하다

이것을 변경하면 post조금 까다로워집니다. 처리 방법은 다음과 같습니다.

 it "responds with JSON" do
    my_model = stub_model(MyModel,:save=>true)
    MyModel.stub(:new).with({'these' => 'params'}) { my_model }
    post :create, :my_model => {'these' => 'params'}, :format => :json
    response.body.should == my_model.to_json
  end

mock_model에 응답하지 않습니다 to_json그래서 중 하나, stub_model또는 실제 모델 인스턴스가 필요합니다.


답변

다음과 같이 응답 본문을 구문 분석 할 수 있습니다.

parsed_body = JSON.parse(response.body)

그런 다음 구문 분석 된 컨텐츠에 대해 어설 션을 작성할 수 있습니다.

parsed_body["foo"].should == "bar"


답변

의 오프 구축 케빈 트로 브리지의 대답

response.header['Content-Type'].should include 'application/json'


답변

json_spec gem 도 있습니다.

https://github.com/collectiveidea/json_spec


답변

간단하고 쉬운 방법입니다.

# set some variable on success like :success => true in your controller
controller.rb
render :json => {:success => true, :data => data} # on success

spec_controller.rb
parse_json = JSON(response.body)
parse_json["success"].should == true


답변

내부에 도우미 함수를 정의 할 수도 있습니다 spec/support/

module ApiHelpers
  def json_body
    JSON.parse(response.body)
  end
end

RSpec.configure do |config|
  config.include ApiHelpers, type: :request
end

json_bodyJSON 응답에 액세스해야 할 때마다 사용 하십시오.

예를 들어 요청 사양 내에서 직접 사용할 수 있습니다.

context 'when the request contains an authentication header' do
  it 'should return the user info' do
    user  = create(:user)
    get URL, headers: authenticated_header(user)

    expect(response).to have_http_status(:ok)
    expect(response.content_type).to eq('application/vnd.api+json')
    expect(json_body["data"]["attributes"]["email"]).to eq(user.email)
    expect(json_body["data"]["attributes"]["name"]).to eq(user.name)
  end
end


답변

JSON 응답 만 테스트하는 다른 방법 (내의 내용에 예상 값이 포함되어 있지 않음)은 ActiveSupport를 사용하여 응답을 구문 분석하는 것입니다.

ActiveSupport::JSON.decode(response.body).should_not be_nil

응답이 구문 분석 가능한 JSON이 아닌 경우 예외가 발생하고 테스트가 실패합니다.