我尝试为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
测试通过了。但是,当我尝试像这样使用let
和subject
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未定义方法`响应'为......”
这让我感到困惑!
答案 0 :(得分:2)
不要设置subject
。控制器规范的主题是控制器,而不是模型对象。只需删除设置subject
的行,就不应再出现该错误。
答案 1 :(得分:1)
it {should respond_with :ok}
我假设此行占用subject
并进行response
调用。
推荐的语法是:
it "returns 200" do
expect(response).to be_success
end
或者您的json_response
辅助方法正在使用subject.response
而不是response
。