如何用RSpec测试这种破坏行为?

时间:2013-11-06 11:15:45

标签: ruby-on-rails ruby-on-rails-3 rspec

在我的Rails应用中,如果user想要删除自己的帐户,他首先必须在terminate视图中输入密码:

<%= form_for @user, :method => :delete do |f| %>

  <%= f.label :password %><br/>
  <%= f.password_field :password %>

  <%= f.submit %>

<% end %>

这是我的UsersController

def terminate
  @user = User.find(params[:id])
  @title = "Terminate your account"
end

def destroy
  if @user.authenticate(params[:user][:password])
    @user.destroy
    flash[:success] = "Your account was terminated."
    redirect_to root_path
  else
    flash.now[:alert] = "Wrong password."
    render :terminate
  end
end

问题是我似乎找不到用RSpec测试这个的方法。

我拥有的是:

describe 'DELETE #destroy' do

  before :each do
    @user = FactoryGirl.create(:user)
  end

  context "success" do

    it "deletes the user" do
      expect{ 
        delete :destroy, :id => @user, :password => "password"
      }.to change(User, :count).by(-1)
    end

  end

end

然而,这给了我一个错误:

ActionView::MissingTemplate:
Missing template users/destroy, application/destroy with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder]}. Searched in:
* "#<RSpec::Rails::ViewRendering::EmptyTemplatePathSetDecorator:0x007fa7f51310d8>"

有人能告诉我我在这里缺少什么或建议更好的方法来测试这个动作吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:12)

好的,这是我的解决方案:

describe 'DELETE #destroy' do

  context "success" do

    it "deletes the user" do
      expect{ 
        delete :destroy, :id => @user, :user => {:password => @user.password}
     }.to change(User, :count).by(-1)
    end

  end

end

我以前的before :each电话是没用的(毕竟这不是集成测试)。密码必须像这样传递::user => {:password => @user.password}在阅读this thread之前我不知道。