【问题标题】:How to test my destroy action with RSpec?如何使用 RSpec 测试我的销毁操作?
【发布时间】:2013-10-22 08:50:50
【问题描述】:

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

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

感谢您的帮助。

【问题讨论】:

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


【解决方案1】:

我播种的第一个错误是:

在销毁操作中你有params[:user][:password],但在测试中你只给params[:id]params[:password]

在控制器中,您在 before_filter 中创建 @user

【讨论】:

    【解决方案2】:

    根据Rspec docsViews are stubbed by default。所以,我认为你应该在测试方法中添加controller.prepend_view_path 'users/destroy'

    【讨论】:

    • 谢谢,但不幸的是没有帮助。
    • 也许,添加controller.prepend_view_path 'app/views',从文档中不清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多