在 RSpec 中使用 let 和 subject 时未定义的方法响应

Undefined method response when using let and subject in RSpec

我尝试为 Rails API

中的 "show" 操作编写一些测试
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

测试通过。但是,当我尝试像这样使用 letsubject

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

显示"NoMethodError undefined method `response' for ..."

这让我很困惑!

不要设置 subject。控制器规范的主题是控制器,而不是模型对象。只需删除设置 subject 的行,您就不会再收到该错误了。

it {should respond_with :ok}

我假设此行采用 subject 并进行 response 调用。 推荐的语法是:

it "returns 200" do
  expect(response).to be_success
end

或者您的 json_response 辅助方法可能使用 subject.response 而不是 response