【问题标题】:testing PUT update is not working on RSPEC ( Ruby on Rails)测试 PUT 更新不适用于 RSPEC(Ruby on Rails)
【发布时间】:2012-10-10 16:40:38
【问题描述】:

所以我正在 RSPEC 中测试我的一个控制器,并且我正在尝试测试整个更新的恶作剧。这就是我在 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

这就是我在控制器中所拥有的

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,因为我的错误表明名称根本没有改变。知道有什么问题吗?

【问题讨论】:

    标签: ruby-on-rails-3 rspec


    【解决方案1】:

    我不知道如何在 get 或 post 参数中传递对象。无论如何尝试这样 描述'PUT更新'做 之前:每个都做 @user = Factory(:user,name: "劳伦斯·史密斯") 结束

      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
    

    我想你已经明白我在这里解释的内容了。

    谢谢

    【讨论】:

    • 但是那不是只允许用户只更新name属性吗?
    • @DaigoUmehara 当然,在这种情况下只能更新名称。
    • 我试过你的方法,他们说它无法识别控制器中的方法或变量名。此外,我根本不希望更改控制器的任何方面,我确实希望用户也能够修改所有其他属性。还是谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    相关资源
    最近更新 更多