2016-01-26 82 views
0

我正在使用jsonapi-serializers gem,并且在计算如何测试rspec和json负载的post请求时遇到了一些麻烦。我知道它可行,因为我可以使用邮递员并发送json并成功创建新对象,但我不确定为什么我无法使rspec测试正常工作。使用Rails测试rspec帖子JSONAPI :: Serializer

这里的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只是一个是我该控制器目前RSpec的试验JSONAPI::Serializer.serialize

这里帮手:

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 

我已经尝试了几乎不同的东西,不知道如何解决这个问题。如果我使用Postman和该确切的json有效负载发布该网址,则会成功创建新节。

获取请求测试工作正常,我只是不知道如何处理rspec和jsonapi序列化器的json请求数据。

回答

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 
+0

谢谢,帮助! – mikeLspohn