【问题标题】:How to properly format RSpec update test如何正确格式化 RSpec 更新测试
【发布时间】:2017-04-07 06:02:09
【问题描述】:

我正在学习如何在 Rails 中测试控制器。我的帖子控制器中有此操作:

def update 
    @post = Post.new(post_params)
    if @post.save 
        redirect_to posts_path
        flash[:success] = "Your post has been updated"
    else 
        render 'edit'
    end 
end 

相当基本的更新操作。我想测试一下。这是我现在的测试:

需要'rails_helper'

RSpec.describe PostsController, type: :controller do 

 let!(:test_post) { Post.create(title: "testing", body: "testing") }

 describe "PUT update" do 
    context "when valid" do 
        it "updates post" do 
            patch :update, id: test_post, post: {title: 'other', body: 'other'}
            test_post.reload
            expect(test_post.title).to eq('other')
        end
    end 
 end 
end

此测试未通过。这是我从 RSpec 得到的错误:

1) PostsController PUT update when valid updates post
 Failure/Error: expect(test_post.title).to eq('other')

   expected: "other"
        got: "testing"

   (compared using ==)

我希望得到一些指导。谢谢!

【问题讨论】:

  • 你在做post :update 而不是patch :update。 Rails 使用put/patch 更新记录。
  • 我实际上是不小心把它留在里面的。改变了它,它仍然失败。有什么想法吗?

标签: ruby-on-rails rspec


【解决方案1】:

在您的更新操作中,您正在创建一个新的Post,而不是更新现有的Post

def update 
  @post = Post.new(post_params) <= here
  if @post.save 
    redirect_to posts_path
    flash[:success] = "Your post has been updated"
  else 
    render 'edit'
  end 
end 

您需要找到现有的Post 记录,然后对其进行更新。这可能看起来更像:

def update 
  @post = Post.find_by(id: params[:id]) <= might need to be different depending on how you have structured your params
  if @post.update_attributes(post_params)
    redirect_to posts_path
    flash[:success] = "Your post has been updated"
  else 
    render 'edit'
  end 
end 

【讨论】:

  • 谢谢!有时我需要第二双眼睛。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 2022-01-13
  • 2023-04-09
  • 1970-01-01
  • 2017-02-27
  • 1970-01-01
  • 2012-06-13
相关资源
最近更新 更多