2014-02-22 63 views
-1

我在學習RSpec時遇到了問題,我無法弄清楚我做錯了什麼。重定向測試的Rails4/devise/rspec問題

這是我的控制器代碼:

def create 
    @item = Item.new(item_params) 
    if current_user 
    @item.user_id = current_user.id 
    end 
    respond_to do |format| 
    if @item.save 
     format.html { redirect_to @item, notice: 'item was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @item } 
    else 
     format.html { render action: 'new' } 
     format.json { render json: @item.errors, status: :unprocessable_entity } 
    end 
    end 
end 

我controller_spec:

it "renders new page again if validation fails" do 
user = User.new(email:"[email protected]", password:"tomandjerry") 
sign_in user 
post :create, item: { name:"Hi"} 
expect(response).to redirect_to("/items/new") 
end 

而且我有

include Devise::TestHelpers 
我controller_spec

config.include Devise::TestHelpers, :type => :controller 

in spec_helper。

看起來不錯,但我碰上

 ←[31m Expected response to be a redirect to <http://test.host/items/new> 
but was a redirect to <http://test.host/users/sign_in>.←[0m 

錯誤。

請問你能提出我做錯了什麼?

回答

0

您沒有創建用戶,只是初始化對象。做到這一點,而不是:

user = User.create!(email:"[email protected]", password:"tomandjerry")

作爲一個方面說明,我會建議你使用導軌裝置或factory_girl用於這一目的。

+0

這樣做,謝謝。 至於燈具 - 我會學習和使用,當然,我只是想嘗試一些基本的測試。 – user3115061