嵌套资源的RSpec控制器,before_action

时间:2016-05-23 19:31:36

标签: ruby-on-rails ruby ruby-on-rails-4 rspec rspec3

我说我的设置是这样的:

配置/ routes.rb中

  resources :graves do
    resources :candles
  end

应用程序/模型/ grave.rb

has_many :candles, dependent: :destroy

应用程序/模型/ candles.rb

belongs_to :grave

应用程序/控制器/ candles_controller.rb

before_action :get_grave

def create
  @candle = @grave.candles.new(candle_params)
    respond_to do |format|
      if @candle.save
        format.html {
          redirect_to @grave, notice: 'Candle was successfully created.'
        }
        format.json { }
      else
        format.html { render :new }
        format.json { render json: @candle.errors, status: :unprocessable_entity }
      end
    end
end

private
def candle_params
  params.require(:candle).permit(:name, :body)
end

def get_grave
  @grave = Grave.find(params[:grave_id])
end

规格/控制器/ candles_controller_spec.rb

describe CandlesController, type: :controller do
  describe "POST create" do
    before(:each) do
      @grave = FactoryGirl.create(:grave)
    end
    it "creates candle" do
      post :create, candle: { name: "Dummy name", body: "Dummy body", grave_id: @grave.id}
      expect(response).to redirect_to(@grave)
    end
  end
end

问题是当我运行此规范时出现此错误:

  

1)CandlesController POST创建蜡烛        失败/错误:期待(响应).to redirect_to(@grave)          预期的响应是<重定向>,但是< 404>

我已经检查了FactoryGirl并创建了@grave,因此它不是零。我手动测试时candle已正确创建并且与grave相关联。什么可能导致规范失败的线索?

Rails 4.2,RSpec 3.x

1 个答案:

答案 0 :(得分:1)

您的路线如下所示:graves/:grave_id/candles,因此您必须将@grave.id方法作为post传递给grave_id方法。

post :create, grave_id: @grave.id, candle: { name: "Dummy name", body: "Dummy body", grave_id: @grave.id}