[英]Factory Girl & Rspec controller test failure
我對測試還是相當陌生,並且仍然將我的頭纏在Factory Girl上,我認為這是這次失敗的罪魁禍首。 該解決方案可能會很簡單,但我搜索了其他帖子,但帶有相同的失敗消息,但答案對我不起作用。
我決定通過構建此簡單的博客應用程序來學習BDD / TDD。 這是失敗消息:
Failures:
1) PostsController POST create creates a post
Failure/Error: expect(response).to redirect_to(post_path(post))
Expected response to be a <redirect>, but was <200>
考試:
RSpec.describe PostsController, :type => :controller do
let(:post) { build_stubbed(:post) }
describe "POST create" do
it "creates a post" do
expect(response).to redirect_to(post_path(post))
expect(assigns(:post).title).to eq('Kicking back')
expect(flash[:notice]).to eq("Your post has been saved!")
end
end
end
我的工廠女郎文件:
FactoryGirl.define do
factory :post do
title 'First title ever'
body 'Forage paleo aesthetic food truck. Bespoke gastropub pork belly, tattooed readymade chambray keffiyeh Truffaut ennui trust fund you probably haven\'t heard of them tousled.'
end
end
控制器:
class PostsController < ApplicationController
def index
@posts = Post.all.order('created_at DESC')
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
flash[:notice] = "Your post has been saved!"
else
flash[:notice] = "There was an error saving your post."
end
redirect_to @post
end
def show
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
如果相關,這是我的Gemfile:
gem 'rails', '4.1.6'
...
group :development, :test do
gem 'rspec-rails', '~> 3.1.0'
gem 'factory_girl_rails', '~> 4.5.0'
gem 'shoulda-matchers', require: false
gem 'capybara'
end
任何幫助表示贊賞。
嘗試以下方法進行測試:
context 'with valid attributes' do
it 'creates the post' do
post :create, post: attributes_for(:post)
expect(Post.count).to eq(1)
end
it 'redirects to the "show" action for the new post' do
post :create, post: attributes_for(:post)
expect(response).to redirect_to Post.first
end
end
就我個人而言,我還會將您的一些期望與其他測試分開。 但是,我不知道在控制器中是否真的需要測試以這種方式設置它們。
編輯:您的創建操作還有一個問題,如果未成功保存,它仍將嘗試重定向到@post,這將失敗。 具有無效屬性的測試應突出顯示這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.