如何正确格式化RSpec更新测试

时间:2017-04-06 21:48:25

标签: ruby-on-rails rspec

我正在学习如何在Rails中测试控制器。我在帖子控制器中有这个动作:

<head lang="en">
    <title>The Quiz</title>
</head>
<body>

<div class="grid">
    <div id="quiz" class="centered grid__col--8">
        <h1>Quiz</h1>

        <h2 id="question" class="headline-secondary--grouped"></h2>
        <h3 id="score"></h3>

        <p id="choice0"></p>
        <button id="guess0" class="btn--default">Select Answer</button>

        <p id="choice1"></p>
        <button id="guess1" class="btn--default">Select Answer</button>

        <footer>
            <p id="progress">Question x of y</p>
        </footer>
    </div>
</div>
</body>

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

需要'rails_helper'

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 

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

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

我很感激一些指导。谢谢!

1 个答案:

答案 0 :(得分:2)

在您的更新操作中,您要创建新的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