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

时间:2017-03-10 17:53:33

标签: ruby-on-rails ruby rspec

编写一些控制器测试,使用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)忽略Rails链接,它与测试无关 (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 %>的快速测试部分传递绿色。如何将变量@order传递到_used部分现在是个问题。

3 个答案:

答案 0 :(得分:0)

尝试添加规范类型。

我相信动作控制器URL帮助程序包含在规范类型中。

尝试:

describe SomeController, type: :controller do

答案 1 :(得分:0)

您可以根据文件位置

设置规格类型,而不是手动设置规格类型
# 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

答案 2 :(得分:0)

首先,我需要将其更改为order_pathorders_path错误。卫生署。

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

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

最终,将方法assign_promo_to_users_order存根,为current_user指定一个完整的顺序就可以了:

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