RSpec破坏动作错误-没有路线匹配

时间:2019-01-13 02:15:30

标签: ruby-on-rails rspec

我正在尝试为我的user_stocks_controller的销毁操作编写一个rspec测试,但出现错误:

  

UserStocksController DELETE #destroy删除库存失败/错误:   删除:destroy,参数:{id:user_stock.id}

     

ActionController :: UrlGenerationError:没有路由匹配   {:action =>“ destroy”,:controller =>“ user_stocks”,:id => nil}

我已阅读到该问题存在,因为我没有提供股票ID。我试图以多种不同的方式进行更改,但我的想法是错误的。

这是我的规格:

let(:user) { User.new(email: 'test@example.com', password: 'password') }

  before do
    sign_in(user)
  end

 describe 'DELETE #destroy' do
    let(:stock) { Stock.new_from_lookup('GS') }
    let(:user_stock) { UserStock.create(user: user.id, stock: stock) }

    it 'deletes stock' do
      expect do
        delete :destroy, params: { id: user_stock.id }
      end.to change(UserStock, :count).by(-1)
      expect(response).to have_http_status(redirect)
      expect(flash[:notice]).to eq 'Stock successfully removed'
    end
  end

user_stocks_controller中的销毁方法:

  def destroy
    stock = Stock.find(params[:id])
    @user_stock = UserStock.where(user_id: current_user.id, stock_id: stock.id).first
    @user_stock.destroy!
    flash[:notice] = 'Stock successfully removed'
    redirect_to my_portfolio_path
  end

为什么即使我设置了id也没有检测到我的路线?

2 个答案:

答案 0 :(得分:0)

您正在使用哪个版本的rails?在rspec-rails github存储库中有一些示例,说明如何根据<5的rails或> 5的rails进行销毁,其语法不同。

如果rails版本是<5,请尝试

delete :destroy, {id: user_stock.id}

另一种解决方案是尝试使用删除路径,以便根据您的路线,如下所示

delete "/user_stocks/#{user_stock.id}"

答案 1 :(得分:0)

您好,我正在与Rails 5.2.3合作,而我的解决方案如下:

delete "/user_stocks/#{user_stock.id}"

但是,正如我在此线程上的一些评论中遇到的No route matches错误一样,我的解决方案很简单,只需在user_stock调用之前保存delete对象。在我的情况下,我正在使用声明为UserStock.new的对象进行测试,因此它没有ID,这就是delete调用启动No route matches的原因,因为它是通过此路径{{ 1}},而不是/user_stocks/

希望这项工作!