I am new to rspec. I am getting failure message as shown below:
Failures:
1) PostsController PUT update it success when update a post
Failure/Error: expect(response).to redirect_to(posts_url)
Expected response to be a <redirect>, but was <200>
# ./spec/controllers/posts_controller_spec.rb:11:in `block (3 levels) in <top (required)>'
Finished in 0.24448 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/controllers/posts_controller_spec.rb:8 # PostsController PUT update it success when update a post
I have following codes in posts_controller_spec.rb
require 'spec_helper'
describe PostsController do
describe "PUT update" do
let(:post) {FactoryGirl.create(:post)}
it "it success when update a post" do
@post = FactoryGirl.create(:post, :title => "my title", :content => "my content")
expect {put :update, :id => @post.id }
// put :update, { :id => @post.id, :post => { "title" => "MyString", :content => "my content" } }
expect(response).to redirect_to(posts_url)
end
end
end
I got many solutions, but did not get success.
I am getting issue in this line
expect(response).to redirect_to(posts_url)
I tried below code as well
specify { expect(response).to redirect_to(posts_path) }
FYI I have added below codes to my spec_helper.rb
RSpec.configure do |config|
config.mock_with :rspec do |c|
c.syntax = [:should, :expect]
end
config.expect_with :rspec do |c|
c.syntax = [:should, :expect]
end
Any suggestion would be much appreciated.
posts_controller.rb is something like this.
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id]
end
def update
@post = Post.find(params[:id])
if @post.update_attributes(post_params)
redirect_to posts_path
else
render :action => :edit
end
end
def index
@posts = Post.all
end
private
def post_params
params.require(post).permit!
end
end
class Post < ActiveRecord::Base
validates :title, :content, :presence => true
end
According your controller, @post
never updated because post_params
empty, so update
action render edit
template with status 200
.
Try change your it
block to update @post
variable(this is just example):
it "it success when update a post" do
@post = FactoryGirl.create(:post, :title => "my title", :content => "my content", :id => 3)
put :update, :id => @post.id, FactoryGirl.attributes_for(:post)
expect(response).to redirect_to(posts_url)
end