我正在为我的观点写测试。我碰巧有一个动作的 html 和 json 视图,但我不知道如何强制 rspec 使用给定的格式。
目前我将我的代码最小化为以下内容:
# cat spec/views/services/index.json.jbuilder_spec.rb
require 'spec_helper'
describe "services/index" do
let(:services) { 3.times.map { FactoryGirl.create(:service) } }
before(:each) { assign(:services, services) }
let(:resp) do
render template: 'services/index', format: :json # note the format here
JSON.parse(response.body, simbolize_names: true)
end
it("should be an array") { resp.should be_kind_of(Array) }
end
但它仍然呈现 HTML 代码。我收到错误
Failure/Error: JSON.parse(response.body, simbolize_names: true)
JSON::ParserError:
757: unexpected token at '<h1>Listing services</h1>
[cut rest of HTML]
我的json视图很简单
# cat app/views/services/index.json.jbuilder
json.array! @services, *Service.json_attributes
我的 html 视图的前 5 行是
# cat app/views/services/index.html.haml | head -5
%h1 Listing services
%table
%tr
%th Logo
如果我尝试在渲染模板中传递格式,例如
render template: 'services/index.json'
我得到以下信息:
DEPRECATION WARNING: Passing a template handler in the template name is
deprecated. You can simply remove the handler name or pass render
我的 rspec 是 2.13.1 版,在 ruby 2.0 上运行。