2012-10-10 35 views
-1

因此,我正在測試RSPEC中的一個控制器,並且正在嘗試測試整個升級shenanigans。這就是我在RSPEC測試PUT更新不適用於RSPEC(Ruby on Rails)

describe 'PUT update' do 
     before :each do 
      @user = Factory(:user,name: "Lawrence Smith") 
     end 

     context "valid attributes" do 
     it "located the requested @user" do 
      put :update, :id => @user, user: Factory.attributes_for(:user) 
      assigns(:user).should eq(@user)  
     end 

     it "changes @user's attributes" do 
      put :update, :id=> @user.id, user: Factory.attributes_for(:user, name: "Larry Smith") 
      @user.reload 
      @user.name.should eq("Larry Smith") 

     end 

     end 

而這正是我在控制器

def update 
#update and save 
@user = User.find(params[:id]) 
respond_to do |format| 
if @user.update_attributes(params[:user]) 
    sign_in @user 
    format.json{render :json => @user ,:status => :created, :location => @user } 
else 
    format.json { render :json => @user.errors, :status => :unprocessable_entity } 
end 
end 

末 所以顯然在@ user.reload並沒有真正刷新的ActiveRecord,如我的錯誤顯示名字一直沒有改變。任何想法有什麼不對?

回答

0

我不知道如何在get或post參數中傳遞對象。不管怎麼說嘗試這樣 描述 'PUT更新' 做 前:每個做 @user =廠(:用戶名: 「勞倫斯·史密斯」) 結束

context "valid attributes" do 
    it "located the requested @user" do 
     put :update, :id => @user, user: Factory.attributes_for(:user) 
     assigns(:user).should eq(@user)  
    end 

    it "changes @user's attributes" do 
     put :update, :id=> @user.id, :user_name => Factory.attributes_for(:user, name: "Larry Smith").name 
     @user.reload 
     @user.name.should eq("Larry Smith") 

    end 

    end 

,這在控制器

def update 
#update and save 
@user = User.find(params[:id]) 
respond_to do |format| 
if @user.update_attributes(:name => params[:user_name]) 
    sign_in @user 
    format.json{render :json => @user ,:status => :created, :location => @user } 
else 
    format.json { render :json => @user.errors, :status => :unprocessable_entity } 
end 
end 

我想你會得到我在這裏解釋的。

謝謝

+0

但是,不會只允許用戶只更新name屬性嗎? –

+0

@DaigoUmehara ofcourse,在這種情況下只能更新名稱。 –

+0

我試過你的方式,他們說它不能識別控制器中的方法或變量名稱。此外,我不希望控制器的任何方面都有所改變,我希望用戶能夠修改所有其他屬性。不管怎麼說,還是要謝謝你 –