How to send params with FactoryGirl (as opposed to manually sending the params as a hash)?
Asked Answered
R

2

9

I have the following rspec test that works:

  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

But I use Factory girl so I don't have to manually create api_keys.

How can I replicate the above functionality, but use factory girl?

Using:

  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

or:

  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

Gives me null values for the :api_key value when I arrive at my controller.

For reference, here is my create action that this test is testing:

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
Refinery answered 26/2, 2013 at 15:57 Comment(0)
K
27

try:

post :create, :api_key => FactoryGirl.attributes_for(:api_key)
Koziel answered 26/2, 2013 at 16:0 Comment(0)
S
1

Using build doesn't actually create a record. It just pretends it did. Using attributes_for will give you the attributes of an object. This is mostly used in the context you describe. Note that this too will not create an object.

What I would do is this if the response is successful/redirect:

 response.should be_redirect

Or even better use expect.

Shaina answered 26/2, 2013 at 16:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.