Rails4 / devise / rspec问题与重定向测试

时间:2014-02-22 16:10:28

标签: ruby-on-rails rspec 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:"test@email.com", 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

在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

错误。

你能否建议我做错了什么?

1 个答案:

答案 0 :(得分:0)

您不是在创建用户,而只是初始化对象。这样做:

user = User.create!(email:"test@email.com", password:"tomandjerry")

作为旁注,我建议你为此目的使用rails fixtures或factory_girl。