【问题标题】:Undefined method response when using let and subject in RSpec在 RSpec 中使用 let 和 subject 时未定义的方法响应
【发布时间】:2016-06-04 23:22:00
【问题描述】:

我尝试为 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

测试通过了。但是,当我尝试像这样使用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 ...”

这让我很困惑!

【问题讨论】:

    标签: ruby-on-rails ruby rspec rspec-rails


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      it {should respond_with :ok}
      

      我假设这条线接受subject 并拨打response 电话。 推荐的语法是:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-21
        • 2013-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多