如何使用FactoryGirl发送params(而不是手动将params作为哈希发送)?

时间:2013-02-26 15:57:20

标签: ruby-on-rails ruby ruby-on-rails-3 rspec factory-bot

我有以下有效的rspec测试:

  it "redirects to the created api_key" do
    post :create, :api_key => {:api_identifier => "asdfadsf", :verification_code =>
        "12345"}
    response.should redirect_to(ApiKey.last) #(or any other test function)
  end

但我使用Factory girl,所以我不必手动创建api_key s。

我如何复制上述功能,但使用工厂女孩?

使用:

  it "redirects to the created api_key" do
    test = FactoryGirl.build(:api_key)
    post :create, :api_key => test
    response.should redirect_to(ApiKey.last) #(or any other test function)
  end

或:

  it "redirects to the created api_key" do
    post :create, FactoryGirl.build(:api_key)
    response.should redirect_to(ApiKey.last) #(or any other test function)
  end

当我到达我的控制器时,给我:api_key值的空值。

作为参考,这是我的测试正在测试的创建操作:

def create
  @api_key = ApiKey.new(params[:api_key])
  @api_key.user = current_user
  pp @api_key

  respond_to do |format|
    if @api_key.save
      format.html { redirect_to @api_key, notice: 'Api key was successfully created.' }
      format.json { render json: @api_key, status: :created, location: @api_key }
    else
      format.html { render action: "new" }
      format.json { render json: @api_key.errors, status: :unprocessable_entity }
    end
  end
end

2 个答案:

答案 0 :(得分:26)

尝试:

post :create, :api_key => FactoryGirl.attributes_for(:api_key)

答案 1 :(得分:1)

使用build实际上并不创建记录。它只是假装它做了。使用attributes_for将为您提供对象的属性。这主要用于您描述的上下文中。请注意,此也不会创建对象。

如果响应成功/重定向,我会怎么做:

 response.should be_redirect

甚至更好地使用expect