2013-02-26 2 views
9

나는 작동 다음 RSpec에 시험이 있습니다FactoryGirl에서 매개 변수를 보내는 방법 (수동으로 매개 변수를 해시로 보내는 것과 반대)?

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 

을하지만 수동으로 api_key의를 만들 필요가 없습니다 그래서 나는 공장 소녀를 사용합니다.

어떻게하면 위 기능을 복제 할 수 있습니까?

사용 :

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 값에 대한 null 값을 제공합니다.

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 

답변

25

시도 :

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

내 하루를 보냈습니다! 많은 감사합니다 !! – Hito

1

실제로 레코드를 생성하지 않습니다 build를 사용

는 참고로, 여기이 테스트는 테스트입니다 내 만드는 작업입니다. 그냥 그랬던 것처럼. attributes_for을 사용하면 객체의 속성을 얻을 수 있습니다. 이것은 주로 사용자가 설명하는 컨텍스트에서 사용됩니다. 이 은 개체를 만들지 않습니다.

내가 할 것이라고하는 응답이 성공하면이/리디렉션입니다 :

response.should be_redirect 

또는 더 나은 expect를 사용합니다.

관련 문제