我试图为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的行,就不应该再出现该错误。

关于ruby-on-rails - 在RSpec中使用let和subject时未定义的方法响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37635967/

10-13 04:46