2014-03-27 32 views
0

我在做什麼錯?失敗/錯誤:expect(迴應).to render_template(:new)

Failures:

1) AccountsController POST :create an account that already exists renders the :new template Failure/Error: expect(response).to render_template(:new) expecting <"new"> but rendering with <[]> # ./spec/controllers/accounts_controller_spec.rb:131:in `block (4 levels) in '

Finished in 0.26832 seconds 34 examples, 1 failure

Failed examples:

rspec ./spec/controllers/accounts_controller_spec.rb:128 # AccountsController POST :create an account that already exists renders the :new template

驗證我的代碼是由在軌運行控制檯它正確地寫道:當我rspec的運行我不斷收到此錯誤。而且足夠真實,它呈現:new模板,甚至返回200.我通過在rails控制檯中使用應用程序對象來做到這一點。輸出如下:

Started POST "/accounts" for 127.0.0.1 at 2014-03-26 21:18:06 -0700 
Processing by AccountsController#create as HTML 
Parameters: {"account"=>{"name"=>"name", "description"=>"desc", "opening_balance"=>"1.0"}} 
(0.1ms) begin transaction 
Account Exists (0.2ms) SELECT 1 AS one FROM "accounts" WHERE "accounts"."name" = 'name' LIMIT 1 
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message. 
(0.1ms) rollback transaction 
**Rendered accounts/new.html.erb within layouts/application (1.4ms)** 
Completed 200 OK in 44ms (Views: 32.8ms | ActiveRecord: 0.3ms) 
=> 200 

這會創建兩次相同的帳戶。我預計,它會失敗,然後重定向到:新模板。 rspec代碼在這裏:

context 'an account that already exists' do 

    it 'renders the :new template' do 
     call_post_create_verb 
     call_post_create_verb 
     **expect(response).to render_template(:new)** 
    end 

    end 

看看else條件,你會發現我渲染的地方:new。控制器代碼是在這裏:

def ceate 
    @account = Account.new(account_params) 
    if @account.save 
    redirect_to @account 
    else 
    **render :new** 
    end 
end 

這是我的設置: 紅寶石2.1.1p76(2014年2月24日修訂45161)x86_64的-darwin13.0] 軌(4.0.3) RSpec的護欄(2.14.1)

+1

你真的打電話創建兩次在你的規範? –

+0

我們需要看到更多的上下文,比如規範的實際內容(什麼是「call_post_create_verb」?) – sevenseacat

+0

清除測試日誌並運行失敗的規範。檢查測試日誌,因爲它可能會指出一些新的信息。 –

回答

0

我認爲您需要將render_views添加到規範中。 RSpec的默認渲染什麼 - 這就是爲什麼你會得到「期待<‘新’>但是< []>渲染」

context 'an account that already exists' do 

    render_views 

    it 'renders the :new template' do 
    call_post_create_verb 
    call_post_create_verb 
    **expect(response).to render_template(:new)** 
    end 

+0

render_views不是答案。我只是試了一下。它沒有工作。 – user1976515

+0

和你得到同樣的錯誤? – gotva

+0

並在測試結束時檢查'response.body'中有什麼?你有沒有空字符串或一些呈現部分「新」? – gotva

1
let(:call_post_create_verb) { post :create, account: valid_info } 

本來模擬創建相同的帳戶兩次,我簡單地稱它爲兩次。它應該工作,但它拒絕。所以,與其說這兩次,我改變了第一次調用:

Account.create valid_info 

所以我先在模型中創建它,然後調用「後打造」重新創建具有相同信息的帳戶,這應該肯定會失敗,因爲我正在驗證name屬性中的唯一性。

這樣做後,它終於奏效了。

+1

這是因爲Rspec的'let'阻止了結果的緩存,所以第一次被調用的時候你實際上做了這個帖子,第二次被調用的時候你只是得到了結果的引用,並沒有實際發出第二個請求。 – Haegin

相關問題