简体   繁体   English

Rspec Rails API控制器索引测试

[英]Rspec rails api controller index test

I'm trying to test an api controller action with rspec, but since i am quite new to rspec i can't make it work. 我正在尝试使用rspec测试api控制器动作,但是由于我对rspec相当陌生,因此无法使其正常工作。 I have the following index action: render json: @website.jobs 我有以下索引操作:渲染json:@ website.jobs

I have to find all associated jobs to a website by name. 我必须按名称查找与网站相关的所有工作。 Here is my spec: 这是我的规格:

let(:endpoint) { FactoryGirl.create(:website) }
let(:job) { FactoryGirl.create(:job) }

subject do
  get :index, params: { format: :json, 
                       name: endpoint.name }
end

expect(subject.body).to include(:job)

Am i doing something wrong, or am i missing something ? 我是在做错什么,还是想念什么?

You cannot check the object directly with the JSON response. 您不能直接使用JSON响应检查对象。 You can do something like this: 您可以执行以下操作:

it "response with JSON body containing expected jobs" do
  hash_body = JSON.parse(response.body)
  expect(hash_body).first.to match({
    id: job.id,
    title: job.title
  })
end

You need to change the attributes according to your Job model. 您需要根据Job模型更改属性。

A good tutorial for testing JSON using Rspec: Pure RSpec JSON API testing 一个使用Rspec测试JSON的好教程: Pure RSpec JSON API测试

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM