【问题标题】:How can this destroy action be tested with RSpec?如何使用 RSpec 测试这种破坏动作?
【发布时间】:2013-11-06 11:15:45
【问题描述】:

在我的 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>"

谁能告诉我我在这里缺少什么或建议更好的方法来测试此操作?

感谢您的帮助。

【问题讨论】:

  • 你得到的错误很奇怪。顺便说一句,您没有发送正确的参数
  • 你准备好相关的视图模板了吗?
  • @NeilBillingham 有了这个实现,OP 不需要 destroy 模板,但是 RSpec 抱怨缺少这个模板。
  • 将测试中的请求行更改为此删除 :destroy, :id => @user.id, :password => "password" 有什么不同吗?
  • @apneadiving:你可能是对的。我总是尽量让我的问题尽可能简短,有时我会被带走。对此感到抱歉。

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


【解决方案1】:

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

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 =&gt; {:password =&gt; @user.password},直到阅读this thread,我才知道。

【讨论】:

  • 为什么我收到 ArgumentError: unknown keywords: id, user
  • 在 Rails 6 中我得到未知的关键字 id ?
猜你喜欢
  • 1970-01-01
  • 2011-10-28
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
相关资源
最近更新 更多