我已经为此苦苦挣扎了几个小时。我正在使用 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/