How can this destroy action be tested with RSpec?

强颜欢笑 提交于 2020-01-03 08:07:46

问题


In my Rails app, if a user wants to delete his own account he will first have to enter his password in my terminate view:

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

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

  <%= f.submit %>

<% end %>

This is my 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

The problem is that I can't seem to find a way to test this with RSpec.

What I have is this:

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

However, this gives me an error:

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

Can anybody tell me what I'm missing here or suggest a better way to test this action?

Thanks for any help.


回答1:


OK, this is my solution:

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

The before :each call I had before was useless (this is not an integration test after all). The password has to be passed in like this: :user => {:password => @user.password} which I didn't know until reading this thread.



来源:https://stackoverflow.com/questions/19810635/how-can-this-destroy-action-be-tested-with-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!