我有一个仅返回 json 的 Rails Controller
def index
if params[:filtered] = 'someValue'
@json = Model.where(some_conditions).to_json
else
@json = Model.where(some_other_conditions).to_json
end
render json: @json
end
测试操作是否返回预期 @json 对象的正确方法是什么?
我尝试过以下方法
describe "GET #index" do
before :each do
get :index, filtered: 'someValue'
end
it { expect( response.body ).to eq 'my expected response' }
end
但是我得到了
Failure/Error: it { expect( response.body ).to eq 'my expected response' }
expected: 'my expected response'
got: "[]"
我无法确定底层 Controller 是否存在问题,或者我是否只是编写了一个糟糕的测试。
response.body
是获取 json 负载的正确方法吗?
感谢帮助!
最佳答案
您的 Controller 和规范都有些偏差。
You don't need to call
to_json
on the object that you want to render. If you use the:json
option, render will automatically callto_json
for you.
http://guides.rubyonrails.org/layouts_and_rendering.html
您的规范给您 "[]"
的原因是 Model.where(some_conditions)
返回一个空集合。空集合在 JSON 中呈现为空数组。
要么示波器未按预期工作,要么您的测试设置有缺陷。请记住,let 变量是延迟加载的,您需要使用 let!
或引用该变量以将记录插入到测试数据库中。
# polyfill for Rails 4. Remove if you are using Rails 5.
let(:parsed_response) { response.body.to_json }
describe "GET #index" do
# or use fixtures / factories
let!(:model) { Model.create!(foo: 'bar') }
before :each do
get :index, filtered: 'someValue'
end
expect(parsed_response.first["id"].to_i).to eq model.id
end
关于ruby-on-rails - 如何在 Controller 测试中验证 json 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40904366/