Rspec控制器测试:未定义的方法'orders_path'



编写一些控制器测试,使用render_views检查一些部分渲染....

describe PromoCodeController do
  render_views
  describe "GET 'show" do
... a bunch of tests
it "renders 'used' partial when promo code has already been used" do
  @promo_code = create(:promo_code)
  @user.stub(:promo_used?).and_return(true)
  get 'show', :slug => @promo_code.slug
  expect(response).to render_template(:partial => 'promo_code/_used')
end

_used中加载

<article>
  <p><%= @promo.description.html_safe %></p>
  <p>Sorry, it appears this promo code has already been used. Please try again or contact us directly.</p>
  <%= link_to "View Order", orders_path(@order), class: "box-button-black", data: { bypass: true } %>
</article>

但与:

打破
undefined method `orders_path' for #<#<Class:0x007fd4069d06e8>:0x007fd401e3e518>

关于如何(a)忽略导轨链接,与测试无关(b)在测试中包括一些以识别链接的东西(c)存根(我认为最后一个度假胜地)

到目前为止我尝试过的一切都无法超越错误。

编辑:

orders_path是错误的,应该是 order_path。更改后,我得到了:

ActionView::Template::Error:
       No route matches {:controller=>"order", :action=>"show", :id=>nil}

因此,部分正在寻找@order。我尝试使用controller.instance_variable_set(:@order, create(:order))设置它,但是在部分中,它以nil返回。

通过在视图部分中添加<% @order = Order.last %>的快速测试。如何将var @order传递到 _used部分是问题。

而不是手动设置规格类型,可以基于文件位置设置

# spec_helper.rb
RSpec.configure do |config|
  config.infer_spec_type_from_file_location!
end 
describe 'GET SHOW' do
  run this in a before block 
  before do 
    controller.instance_variable_set(:@order, create(:order)) 
  end 
  it "renders 'used' partial when promo code has already been used" do
    promo_code = create(:promo_code)
    @user.stub(:promo_used?).and_return(true)
    # check if @order variable is assigned in the controller 
    expect(assigns(:order).to eq order 
    get 'show', slug: promo_code.slug
    expect(response).to render_template(:partial => 'promo_code/_used')
  end
end

首先,我需要将其更改为 order_pathorders_path是错误的。doh。

比我需要一些方法来解决错误

需要的

ActionView::Template::Error:
       No route matches {:controller=>"order", :action=>"show", :id=>nil}

最终,将分配给Current_user分配完整订单的方法assign_promo_to_users_order固定了:

it "renders 'used' partial when promo code has already been used" do
  @promo_code = create(:promo_code)
  @user.stub(:promo_used?).and_return(true)
  User.any_instance.stub(:assign_promo_to_users_order).and_return(create(:order, :complete))
  get 'show', :slug => @promo_code.slug
  expect(response).to render_template(:partial => 'promo_code/_used')
end 

尝试添加规格的类型。

我相信动作控制器URL帮助者被包括在规格类型中。

尝试:

describe SomeController, type: :controller do

最新更新