2012-06-30 25 views
2

基本上發生了什麼是當我在rspec規範中進行集成測試時我正在測試重置密碼功能,並且我使用了第三方派對api電話發送電子郵件。我想要信任第三方API發送電子郵件並完全忽略響應。在與rspec進行集成測試時,在rspec中模擬api調用,同時進行與水豚的集成測試

這是我現在使用的代碼,但它仍然發送電子郵件以及失敗,因爲對send_password_reset(包含第三方API調用的位置)的調用是「不」根據摸查

before(:each) do 
    @client = Factory(:user_with_clients).clients.first 
end 

it 'should send out the email(mock) set a temporary password and take them back to the login page' do 
    # WHEN THE MOCK WAS MOVED HERE THE SPEC PASSSED 
    visit '/client_portal/reset_password/new' 
    fill_in 'email', with: @client.email 
    click_button 'Send password reset' 
    # THIS NEEDED TO BE MOVED TO THE TOP OF THE FUNCTION 
    Client.expects(:send_password_reset).returns(true) 
    current_path.should eq('/client_portal/login') 
    page.should have_content('Check your email') 
    @client.reload 
    @client.tmp_password.should_not eq(nil) 
end 

我不認爲發佈用於創建,這將揭示別的工廠叫,但你認爲會幫助你幫助我,我會做到這一點。

我也嘗試將Cilent.expects更改爲@ client.expects,但我仍然遇到同樣的問題。我沒有被綁定到摩卡框架,因爲這實際上是我做過的第一次模擬。

我也讀過,我不應該嘲笑集成測試中的對象,但我不知道在調用測試時不發送電子郵件的方式。

只是覺得我應該在那裏添加控制器動作,以及在情況下,我應該改變了什麼事......

def create 
    client = Client.find_by_email(params[:email]) 
    if client 
     client.set_tmp_password 
     if client.send_password_reset 
     redirect_to '/client_portal/login', notice: 'Check your email for the password reset link' 
     else 
     redirect_to '/client_portal/login', notice: 'There was an error resetting your password. Please try one more time, and contact support if it doesn\'t work' 
     end 
    else 
     flash.now[:notice] = 'No account with that email address was found' 
     render :new 
    end 
    end 

林收到這個錯誤,當我運行測試

1) Reset a users password user is not logged in valid email address supplied should send out the email(mock) set a temporary password and take them back to the login page 
    Failure/Error: Client.any_instance.expects(:send_password_reset).returns(true) 
    Mocha::ExpectationError: 
     not all expectations were satisfied 
     unsatisfied expectations: 
     - expected exactly once, not yet invoked: #<AnyInstance:Client(id: integer, first_name: string, last_name: string, email: string, password_digest: string, signup_charge: decimal, monthly_charge: decimal, active: boolean, created_at: datetime, updated_at: datetime, monthly_charge_day: integer, sold_by_user_id: integer, tmp_password: string)>.send_password_reset(any_parameters) 
    # ./spec/requests/client_portal/reset_password_spec.rb:14:in `block (4 levels) in <top (required)>' 

SOLUTION

使用從@Veraticus下面的代碼,並將其移動到規範的頂部解決的問題。

回答

3

問題是你沒有調用類的send_password_reset方法;你在那個類的一個實例上調用它。使用此:

Client.any_instance.expects(:send_password_reset).returns(true) 

通過Client.find_by_email發現將有預期建立在它正確的client

+0

不幸的是,沒有解決我的問題。我在代碼中添加了錯誤,這與我之前獲得的錯誤完全相同。它仍然通過第三方api發送電子郵件。我會更新這個以包含更多的規範。也許錯誤在別的地方。 – bloveless

+0

期望需要在測試開始時設置,在click_button之前。 – Veraticus

+0

嘿,嘿,嘿,你是一個真正的。我只需將any_instance代碼移動到函數的頂部。我的假設(糾正我,如果我錯了)是,因爲它是在創建模擬之前訪問該頁面,它沒有將其應用於該對象之前它創建...也許... – bloveless