简体   繁体   中英

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. I have the following index action: render 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. 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.

A good tutorial for testing JSON using Rspec: Pure RSpec JSON API testing

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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