ruby-on-rails - last_response.body 在 Rack::Test rspec 测试中为空(但在实际应用程序中不是)

标签 ruby-on-rails

我已经为此苦苦挣扎了几个小时。我正在使用 Rack::Test 为我的 Rails 3.2 应用程序编写 API 测试。

无论我做什么,last_response 都有一个空的正文(嗯,具体来说它有“{}”,所以 2 个字符)。

以下是测试:

describe "updating a product set with JSON" do
  def app
    ProductSetsController.action(:update)
  end

  let(:update_json) { ... }

  before do
    @product_set = FactoryGirl.build(:product_set)
  end
  it { @failures.should == 0 }

  it "should not increment the product set count" do
    expect { put :update, update_json }.to_not change(ProductSet, :count).by(1)
  end

  it "should increment the conditions count" do
    expect { put :update, update_json }.to change(@product_set.conditions, :count).by(2)
  end

  context "response should be valid" do
    before do
      put :update, update_json
    end
    subject { last_response }
    it { should be_ok }
  end
end

所有这些测试都通过了。但 body 是空的。

奇怪的是,如果我运行实际的应用程序,响应正文肯定不为空。它有关于更新的product_set的JSON。

所以我以某种方式错误地设置了测试。我敢打赌我忽略了一些非常愚蠢的事情,因为这是我第一次使用 Rack::Test。有什么想法吗?

只是想到我可能没有正确设置请求 header 。我还使用 RABL 进行生成。

更新: 问题确实出在 RABL 身上。还没有找到解决方案,但如果我使用:

respond_with(@product_set.update_attributes(get_properties(params)),
  file: 'app/views/product_sets/update.json.rabl', :handlers => [:rabl])

而不是:

respond_with(@product_set.update_attributes(get_properties(params)))

然后它在测试中工作,而两者都在开发或生产中工作。我还确认这不是 Gemfile 问题。

最佳答案

找到答案了。简而言之,请确保在 rspec 文档中的根描述 block 顶部使用关键字“render_views”,以确保正确渲染 View 。

这是一篇有用的文章: https://github.com/nesquena/rabl/wiki/Testing-with-rspec

关于ruby-on-rails - last_response.body 在 Rack::Test rspec 测试中为空(但在实际应用程序中不是),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12483253/

相关文章:

ruby-on-rails - Rake 在 '*.rake' 目录中找不到 'lib/tasks' 文件

ruby-on-rails - 您将哪些部署目录用于 Rails 应用程序(部署到 debian 机器)?

javascript - 部分修复使用ajax的渲染

ruby-on-rails - rails : Creating an "All activity feed" from multiple models

ruby-on-rails - 得墨忒耳法则——你能走多远?

ruby-on-rails - 未定义的方法 `each' 为 "#<Complaigns::ActiveRecord_Relation:0x00000003cfb4c8>":String

ruby-on-rails - 使用事件模型序列化程序呈现状态和数据 JSON 响应

html - Rails 图片 link_to 不工作

ruby-on-rails - CanCan:在除 MainApp 的命名空间中的 load_and_authorize_resource

ruby-on-rails - 如何解决使用MiniMagick操作失败,可能不是图像?原始错误: You must have ImageMagick or GraphicsMagick installed