在Rspec中创建记录时,未定义的方法`stringify_keys'

时间:2011-10-23 02:17:58

标签: ruby-on-rails ruby-on-rails-3.1 rspec2 factory-bot

控制器中有一个用于创建的会话变量。如何设置rspec测试的会话变量?

这是在控制器w / session [eng_dh]中创建的方法:

  def create
    if session[:eng_dh] 

      @category = Category.new(params[:category], :as => :roles_new)    

      if @category.save

        redirect_to categories_path, :notice => 'Category was successfully created.'         
      else
        render :action => "new" 
      end
    else
      redirect_to categories_path, :notice =>"NO access to create category!"
    end
  end 

这是失败的rspec代码:

require 'spec_helper'

describe CategoriesController do
  before(:each) do
    #the following recognizes that there is a before filter without execution of it.
    controller.should_receive(:require_signin)
    controller.should_receive(:require_employee)
  end

  render_views

  describe "Post 'create'" do
    describe "success" do
      before(:each) do
        @category = Factory(:category)
        session[:eng_dh] = true  #THIS LINE CAUSED ERROR ( undefined method `stringify_keys' for "1":String) IN RSPEC TEST!!!
      end

      it "should create a category" do
        lambda do
          post :create, :category => @category
        end.should change(Category, :count).by(1)
      end

      it "should redirect to the category index page" do
        post :create, :category => @category
        response.should redirect_to(categories_path)
      end
    end

  end
end

任何解决方案?感谢。

1 个答案:

答案 0 :(得分:3)

您应该能够使用该语法设置会话变量。

由于您设置了会话变量,undefined method 'stringify_keys' 不是,而是来自@category对象的POST参数构造。 @category对象已保存; post需要哈希值。

正确发送邮件参数将解决它:

@category = Factory.attributes_for(:category)

当您添加会话行时,您的测试开始失败,因为您的控制器只会在会话var到位时尝试保存。如果没有会话var,create什么也不做,但您的Factory行已经保存了该行。这是一个错误的“通行证”。