ruby-on-rails - 如何在 Controller 测试中验证 json 响应?

标签 ruby-on-rails rspec

我有一个仅返回 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 call to_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/

相关文章:

javascript - 如何包含我的 javascript 文件而不单独列出它们?

ruby-on-rails - Rails:将当前用户的已发布项目和未发布项目显示为 ActiveRecord::Relation

ruby-on-rails - 如何在factory_girl中建立/创建多对多关联?

ruby-on-rails - 来自 Michael Hartl 的 RoR 教程第 11 章关注用户的 Rspec 方法 'be_following'

ruby-on-rails - Rspec - 测试方法在另一个方法内收到调用

ruby - RSpec Stub循环中的相同方法

ruby-on-rails - 在 cancan、ability.rb 中使用范围

ruby-on-rails - 如何根据属于第一个模型的另一个模型的属性查询一个模型?

iphone - 使用 Ruby on Rails 签署 iPhone 配置 XML 配置文件

ruby-on-rails - Rspec 请求规范的空响应