如何创建验证 JSON 响应的 rspec 测试?
我有一个组控制器,其方法为 def inbox。
如果用户是组成员,则 inbox 返回一个 JSON 对象。
如果用户不是会员,则收件箱应根据 CanCan 权限进行重定向。
如何编写 rspec 来测试这两个用例?
当前规格:
require 'spec_helper'
describe GroupsController do
include Devise::TestHelpers
before (:each) do
@user1 = Factory.create(:user)
@user1.confirm!
sign_in @user1
@group = Factory(:group)
@permission_user_1 = Factory.create(:permission, :user => @user1, :creator_id => @user1.id, :group => @group)
end
describe "GET inbox" do
it "should be successful" do
get inbox_group_path(@group.id), :format => :json
response.should be_success
end
end
end
路线:
inbox_group GET /groups/:id/inbox(.:format) {:controller=>"groups", :action=>"inbox"}
路线文件:
resources :groups do
member do
get 'vcard', 'inbox'
end
....
end
I have a Groups Controller with a method def inbox.
If the user is a group member then inbox returns a JSON object.
If the user is not a member, then inbox should redirect thanks to CanCan permissions.
How do I write an rspec to test these two use cases?
Current spec:
require 'spec_helper'
describe GroupsController do
include Devise::TestHelpers
before (:each) do
@user1 = Factory.create(:user)
@user1.confirm!
sign_in @user1
@group = Factory(:group)
@permission_user_1 = Factory.create(:permission, :user => @user1, :creator_id => @user1.id, :group => @group)
end
describe "GET inbox" do
it "should be successful" do
get inbox_group_path(@group.id), :format => :json
response.should be_success
end
end
end
Routes:
inbox_group GET /groups/:id/inbox(.:format) {:controller=>"groups", :action=>"inbox"}
Routes File:
resources :groups do
member do
get 'vcard', 'inbox'
end
....
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我就是这样做的:
我没有使用 cancan,因此我无法帮助完成这部分。
This is how I do this:
I'm not using cancan, therefore I cannot help with this part.
有时,验证
response
是否包含有效的 JSON 并显示实际响应可能就足够了,下面是一个示例:Sometimes it might be good enough to verify if
response
contains valid JSON and to show actual response otherwise, here is an example:试试这个:
Try this:
我认为您要做的第一件事是检查响应的类型是否正确,即它的
Content-Type
标头设置为application/json
, 然后,根据您的情况,您可能需要检查响应是否可以解析为 JSON,例如 wik< /a> 建议:
如果您觉得检查 JSON 响应有效性的两个测试太多,您可以将上述两个合并为一个测试。
I think the first thing you want to do is to check that the response is of the correct type, i.e. that it has the
Content-Type
header set toapplication/json
, something along the lines of:Then, depending on your case, you might want to check whether the response can be parsed as JSON, like wik suggested:
And you could merge the above two into a single test if you feel like two tests for checking JSON response validity are too much.
要断言 JSON,您也可以这样做:
此博客提供了更多想法。
To assert JSON you can do this too:
This blog gives some more ideas.