-1

So I'm testing one of my controller in RSPEC and I'm trying to test the whole update shenanigans. This is what i have in the RSPEC

 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

And this is what i have in the controller

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

end So apparently the the @user.reload doesn't really refresh the ActiveRecord, as my errors showed that the name has not been changed at all. Any idea what is wrong?

4

1 回答 1

0

我不知道如何在 get 或 post 参数中传递对象。无论如何尝试像这样描述'PUT更新'之前做:每个做@user = Factory(:user,name:“Lawrence Smith”)结束

  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

我想你得到了我在这里解释的内容。

谢谢

于 2012-10-10T18:27:20.807 回答