2014-12-23 55 views
0

我剛添加了一個新功能到我的模型,並希望用rspec進行測試。似乎我做錯了什麼,因爲我的測試保持失敗,沒有任何東西被存儲在分貝。我想要的是作爲一個用戶阻止另一個用戶。rspec測試不保存分貝

我的用戶模型有以下幾點:

has_many :blockeds 
    has_many :blocked_users, :through=> :blockeds 

我user_controller有以下幾點:

def block 
     block_action = Blocked.new 
     block_action.add_blocked(current_user.id,params[:id]) 
     current_user.blockeds << User.find(params[:id]) 
    end 

    def is_blocked 
     blocked = current_user.blocked_by(current_user.id,params[:id]) 
     blocked 
    end 

我阻止模式有以下幾點:

belongs_to :user_blocking, class_name: 'User' 
    belongs_to :user_blocked, class_name: 'User' 

    def add_blocked(blocking_id,blocked_id) 
    self.user_blocking_id = blocking_id 
    self.user_blocked_id = blocked_id 
    self.save! 
    end 

,這是我的測試:

describe 'Block' do 

    let(:user_one) { Fabricate :user } 
    let(:user_two) { Fabricate :user } 

    it 'should block a user' do 
     post :block, current_user: user_one.to_param, id: user_two.id.to_param, format: :json 
     expect{ 
     post :is_blocked, current_user: user_one.to_param, id: user_two.id.to_param, format: :json 
     }.to eq(user_two) 
    end 
    end 

我想測試user_two是否被user_one阻止。既沒有存儲在數據庫中也沒有。任何幫助?

這就是我得到後,我excecute測試:

expected: #<User id: 2, email: "[email protected]", encrypted_password: "$2a$04$cKnZx8h9nVX1xQOruH6.yeSHIl989EA.amK.fqz4kwz...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2014-12-23 13:48:32", updated_at: "2014-12-23 13:48:32", bio: nil, fb_access_token: "accusamuscumsit", fb_app_id: "essesedmaiores", phone: nil, address: nil, authentication_token: "vH3N1KTz1AVmP8fTRAye", gender: "male", profile_completed: false, zip_code: "95304-2111", state: "Indiana", city: "New Chaunceymouth", latitude: 37.6841772, longitude: -121.3770336, access_code_id: nil, locked_at: nil, cover: nil, fb_global_id: nil, birthday: "1996-02-18", age: 226, channel_id: "mh3_dPdbihISTdX8TCOKkQ", first_name: "Tressa", last_name: "Keeling", access_code_type: nil, facebook_data_updated_at: nil> 
      got: #<Proc:[email protected]/Users/toptierlabs/Documents/projects/kinnecting_backend/spec/controllers/api/users_controller_spec.rb:206> 

回答

0

你傳遞一個塊expect,其目的是在情況下使用,你要評估該塊是如何執行改變環境(例如通過to_change)。它通常在一個事務的上下文中執行,但在你的情況下,它並沒有被執行,因爲你只是將它與eq匹配器一起使用。

如果您想查詢由控制器操作的返回值,你需要檢查的response價值爲:

post :is_blocked, current_user: user_one.to_param, id: user_two.id.to_param, format: :json 
expect(response.body).to eq(user_two.to_json) 

更多關於此見How to check for a JSON response using RSpec?