Leo Le Leo Le - 6 months ago 25
Ruby Question

Undefined method response when using let and subject in RSpec

I tried to write some tests for the "show" action in Rails API

require 'rails_helper'

RSpec.describe AirlinesController, type: :controller do
describe "GET #show" do
before(:each) do
@airline = FactoryGirl.create(:airline)
get :show, id: @airline.id
end

it "should return the airline information" do
airline_response = json_response
expect(airline_response[:name]).to eql @airline.name
end

it {should respond_with :ok}
end
end


The test passed. However, when I try to use
let
and
subject
like this

require 'rails_helper'

RSpec.describe AirlinesController, type: :controller do
describe "GET #show" do
let(:airline) {FactoryGirl.create(:airline)}

subject {airline}

before(:each) do
get :show, id: airline.id
end

it "should return the airline information" do
airline_response = json_response
expect(airline_response[:name]).to eql airline.name
end

it {should respond_with :ok}
end
end


It showed "NoMethodError undefined method `response' for ..."

This makes me confused!

Answer

Don't set the subject. The subject of a controller spec is the controller, not a model object. Just remove the line that sets subject and you shouldn't get that error any more.