我正在尝试编写RSpec测试来测试我使用jbuilder构建的模板,最终为我的API提供JSON数据。我在spec/controllers
测试我的控制器功能有很多测试,但我也想测试我在jbuilder视图中渲染正确的JSON字段。以下是我设置的示例:
# app/views/api/v1/users/create.json.jbuilder
json.first_name user.first_name
# spec/views/api/v1/users/create.json.jbuilder_spec.rb
require 'spec_helper'
describe "api/v1/users/create.json.jbuilder" do
it "renders first_name" do
assign( :user, User.create( :first_name => "Bob" ) )
render
hash = JSON.parse( rendered )
hash.has_json_node( :first_name ).with( "Bob" )
end
end
运行rspec spec/views/api/v1/users/create.json.jbuilder_spec.rb
时得到的是以下错误
Failures:
1) api/v1/users/create.json.jbuilder render a user
Failure/Error: render
ActionView::Template::Error:
undefined local variable or method `user' for #<#<Class:0x007fa2911c3118>:0x007fa29105f2b8>
# ./app/views/api/v1/users/create.json.jbuilder:1:in `_app_views_api_v__users_create_json_jbuilder___3806288263594986646_70168098229960'
# ./spec/views/api/v1/users/create.json.jbulder_spec.rb:6:in `block (2 levels) in <top (required)>'
无论我如何尝试将user
对象分配/创建/传递给模板,它都会失败。知道我可能做错了吗?
答案 0 :(得分:1)
经过多次阅读和迭代后,这才有效:
require 'spec_helper'
describe "api/v1/users/create.json.jbuilder" do
let( :user ) { User.create( :not_strict => true ) }
it "renders first_name" do
render :template => "api/v1/users/create", :locals => { :user => user }, :formats => :json, :handler => :jbuilder
rendered.should have_json_node( :first_name ).with( user.first_name )
end
end
注意:have_json_node
来自api_matchers gem。
答案 1 :(得分:0)
分配方法集实例变量,你的视图应该是@ user.first_name而不是user.first_name,还是部分?如果它是部分你应该做渲染:partial =&gt; ...,如果是模板,则应使用@user