【发布时间】:2015-09-30 03:47:50
【问题描述】:
尝试在我命名为“API::ZipsController”的 Rails 控制器上使用 rspec 构建控制器规范。
控制器接受名为“zip_code”的参数并返回活动记录模型和 200 状态。
但是,当我运行 rspec 时,测试失败并显示 NoMethodError: undefined method 'where' for Zip:Module。我相信这是因为'where'是一个实例方法,而不是一个类方法,所以我需要存根/模拟它?不幸的是,到目前为止我还没有解决这个问题。
zips_controller_spec.rb:
describe API::ZipsController do
require 'spec_helper'
it "returns 200 status with zones data" do
get 'show', zip_code: "V9A1B2"
response.should be_success
end
end
api/zips_controller.rb -(工作):
class API::ZipsController < ApplicationController
def show
zip = Zip.where(zip_code: params[:zip_code].upcase.slice(0..2))
render json: zip, status: 200
end
end
zip.rb(模型):
class Zip < ActiveRecord::Base
def as_json(options)
super(:only => [:zip_code])
end
end
【问题讨论】:
-
您的规范中没有遗漏要求吗?
-
@moeabdol 是的,编辑了我上面的代码帖子以包含“spec_helper”。它一直在我的代码中。
-
你能显示 Zip 类吗?
-
其实哪里是类方法!你能显示 Zip 类吗?
-
@moeabdol 将 zip 类添加到上面的帖子中。它只是用于超级 as_json 定义。我尝试使用“find”而不是 where 但得到错误 'ActiveRecord::RecordNotFound (Couldn't find Zip with 'id'={:zip_code=>"V9A"})' 因为它试图通过 id 找到它,我需要通过 zip_code 列找到“哪里”似乎适用的地方
标签: ruby-on-rails ruby rspec