简单的RSpec redirect_to失败

时间:2015-02-11 06:05:18

标签: ruby-on-rails rspec integration-testing

我有一个控制器从url slug获取product.id并将其分配给@product实例变量。

产品具有状态,如果不是for_sale,则访问" / product / product.id"会将您重定向到root_url

class ProductController < ApplicationController
  before_action :still_available, only: [:new, :create]

def show
  @product = Product.find_by(id: params[:id])
end

  private

    def still_available
      product = Product.find_by(id: params[:id])
      unless product.for_sale?
        redirect_to root_url
      end
    end

应用程序/规格/集成:

require 'rails_helper'

RSpec.describe 'product page', :type => :request do

  it 'redirects to the home page if product sold' do
    get "/product/2"
    expect(response).to redirect_to(root_url)
  end
end

应用程序/测试/装置/产品:

two:
  id: 2
  status: 2

status: 2映射到sold

错误:

Failures:

  1) product page redirects to the home page if product sold
     Failure/Error: get "/product/2"
     NoMethodError:
       undefined method `for_sale?' for nil:NilClass

0 个答案:

没有答案