如何使用 RSpec 测试这种销毁操作? [英] How can this destroy action be tested with RSpec?
问题描述
在我的 Rails 应用中,如果 user
想要删除他自己的帐户,他首先必须在我的 terminate
视图中输入他的密码:
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 %>
这是我的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 进行测试的方法.
The problem is that I can't seem to find a way to test this with 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
但是,这给了我一个错误:
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?
感谢您的帮助.
推荐答案
好的,这是我的解决方案:
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
我之前的 before :each
调用没有用(毕竟这不是集成测试).密码必须像这样传入::user =>{:密码=>@user.password}
直到阅读这个线程.
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.
这篇关于如何使用 RSpec 测试这种销毁操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!