2011-05-13 99 views
15

我有一个组控制器与方法def inbox.如何创建验证JSON响应的rspec测试?

如果用户是一个组成员,然后收件箱返回一个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"} 

routes文件:

resources :groups do 
    member do 
    get 'vcard', 'inbox' 
    end 
    .... 
end 

回答

35

这是怎么做到这一点:

describe "GET index" do 
    it "returns correct JSON" do 
    # @groups.should have(2).items 
    get :index, :format => :json 
    response.should be_success 
    body = JSON.parse(response.body) 
    body.should include('group') 
    groups = body['group'] 
    groups.should have(2).items 
    groups.all? {|group| group.key?('customers_count')}.should be_true 
    groups.any? {|group| group.key?('customer_ids')}.should be_false 
    end 
end 

我不使用康康,因此我无法帮助这部分。

+0

谢谢试过,但我得到一个错误:“失败/错误:得到:收件箱,:格式=>:json ActionController :: RoutingError: 没有路由匹配{:controller =>”groups“,:format => :json,:action =>“inbox”} #./controllers/groups_controller_spec.rb:19 “考虑到rake路由会产生一个奇怪的结果:inbox_group GET /groups/:id/inbox(.:format){:controller = >“groups”,:action =>“inbox”} – AnApprentice 2011-05-13 23:28:36

+1

尝试提供使用url_for获取的路径 - http://apidock.com/rails/ActionDispatch/Integration/RequestHelpers/get – Roman 2011-05-13 23:36:38

+0

这会是什么样子? – AnApprentice 2011-05-13 23:44:04

0

要断言JSON,你也可以这样做:

ActiveSupport::JSON.decode(response.body).should == ActiveSupport::JSON.decode(
    {"error" => " An email address is required "}.to_json 
) 

This博客给出了一些更多的想法。

2

试试这个:

_expected = {:order => order.details}.to_json 
response.body.should == _expected 
2

有时可能不够好,以验证是否response包含有效的JSON,这里有一个例子:

it 'responds with JSON' do 
    expect { 
    JSON.parse(response.body) 
    }.to_not raise_error 
end 
1

我想你想要做的第一件事就是以检查响应是否是正确的类型,即它的Content-Type标头被设置为application/json,沿线的东西:

it 'returns JSON' do 
    expect(response.content_type).to eq(Mime::JSON) 
end 

然后,根据你的情况,你可能要检查的响应是否可以解析为JSON,像wik建议:

it 'responds with JSON' do 
    expect { 
    JSON.parse(response.body) 
    }.to_not raise_error 
end 

而且你可以在上面的两个合并成一个单一的测试,如果你觉得像两个检查JSON响应有效性的测试太多了。