Rspec Capybara ActionView :: Template ::错误:未定义的方法`action'为零:NilClass

时间:2015-02-14 21:17:19

标签: ruby-on-rails ruby rspec capybara bdd

我正在测试名为Orders的模型的编辑视图。

以普通用户身份测试页面工作正常,测试通过:

scenario 'a registered user can actually edit the comment of his order' do
    mycart = create(:cart)
    vest = create(:product, name: 'vest', price: '250000')
    jacket = create(:product, name: 'jacket-1', price: '300000')
    line_vest = create(:line_item, product: vest, unit_price: vest.price, cart: mycart)
    line_jacket = create(:line_item, product: jacket, unit_price: jacket.price, cart: mycart)
    Capybara.current_session.driver.header 'Referer', root_path
    order = create(:order, cart: mycart, user_id: 5)
    user = FactoryGirl.create(:user, id: 5)
    login_as(user)
    visit edit_order_path(order)
    fill_in 'Comment', with: 'This is the best order I have ever done'
    click_button 'Update Order'
    expect(page).to have_content 'This is the best order I have ever done'
  end

如果我尝试与管理员运行相同的测试,并编辑对属于其他用户的订单的评论,则测试失败:

scenario 'an admin can edit the comment of any order' do
    mycart = create(:cart)
    vest = create(:product, name: 'vest', price: '250000')
    jacket = create(:product, name: 'jacket-1', price: '300000')
    line_vest = create(:line_item, product: vest, unit_price: vest.price, cart: mycart)
    line_jacket = create(:line_item, product: jacket, unit_price: jacket.price, cart: mycart)
    Capybara.current_session.driver.header 'Referer', root_path
    order = create(:order, cart: mycart, user_id: 5)
    admin = FactoryGirl.create(:user, :admin)
    login_as(admin)
    visit edit_order_path(order)
    fill_in 'Comment', with: 'This is the best order I have ever done'
    click_button 'Update Order'
    expect(page).to have_content 'This is the best order I have ever done'
  end

我收到了这个错误:

Failure/Error: click_button 'Update Order' 
ActionView::Template::Error:
undefined method `action' for nil:NilClass 

无论如何,如果我运行网络服务器,并且作为管理员尝试更新订单(属于任何用户),它的工作正常,所以它只是测试不起作用。

以下是相关的控制器行:

  before_action :set_order, only: [:show, :update, :edit, :destroy]

 def edit
    unless (@order.user_id == current_user.id) or current_user.admin?
      redirect_to :back, :alert => "You are not authorized to view this page."
    end
  end

  def update
    flash[:notice] = 'Order was successfully updated.' if @order.update(order_params)
    respond_with(@order)
  end

    def set_order
      @order = Order.find(params[:id])
    end

1 个答案:

答案 0 :(得分:1)

我遇到了类似的错误。

如果收到如下错误:

undefined method "method_name" for nil:NilClass

简短说明是您的数据库没有您的视图或控制器需要实例化对象的内容。 例如,如果您有@ currency.get_symbol,则需要创建一个夹具或工厂以将货币插入数据库以供测试通过。

长解释: 您可以阅读this article以获得更高级的解释和解决方案。