2011-05-13 41 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響應有效性的測試太多了。