2013-02-26 58 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值空值,當我在我的控制器到達。

供參考,這是我創造的動作,這個測試的測試:

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 2013-11-27 10:01:42

1

使用build實際上並沒有創造紀錄。它只是假裝它。使用attributes_for會給你一個對象的屬性。這主要用在你描述的上下文中。請注意,這將不會創建一個對象。

我會做的就是這個響應是否成功/重定向:

response.should be_redirect 

甚至更​​好使用expect