Rspec测试在类似情况下失败

时间:2011-06-13 10:46:29

标签: ruby-on-rails ruby rspec

我的控制器中有以下方法:

def create
  @user = User.new(params[:user])
    if @user.save        
      redirect_to log_in_path, notice: 'Signed up!'
    else
      render "new"
    end
end

def destroy
  @user = User.find(params[:id])
  @user.destroy
    redirect_to users_path, notice: 'User was deleted.'
end

和规格:

describe "POST 'create'" do
  it "should allow create user" do
    @user = Factory(:user)
    post 'create', :id => @user
    response.should be_success
  end

describe "DELETE 'destroy'" do     
  it "should delete the user" do
    @user = Factory(:user)
    delete "destroy", :id => @user
    response.should redirect_to users_path
  end
end

我不明白为什么即使在保存对象后存在重定向,创建方法的测试也会通过。如果我设置:

  response.should redirect_to log_in_path

如期望测试将失败,对于 destroy 方法也是如此,如果我将期望切换为:

response.should be_success

它会失败。有什么建议? 感谢

1 个答案:

答案 0 :(得分:3)

您的创建操作的实际响应为200 OK(即使您的模型无效且未保存),这就是您现在正在测试的内容。

除此之外,你的创建测试并不好。创建操作将用户哈希作为参数,而不是用户的ID。 你可能想要这样的东西:

  it "should allow create user" do
    @user = Factory.attributes_for(:user)
    post 'create', :user => @user
    @user.persisted?.should be_true
    response.should be_redirect
  end