[英]Factory Girl & Rspec controller test failure
I am still fairly new to testing and still wrapping my head around Factory Girl, which I believe to be the culprit of this failure. 我对测试还是相当陌生,并且仍然将我的头缠在Factory Girl上,我认为这是这次失败的罪魁祸首。 As simple as the solution will probably be, I have searched other posts with the same failure message but the answers are not working for me.
该解决方案可能会很简单,但我搜索了其他帖子,但带有相同的失败消息,但答案对我不起作用。
I decided to learn BDD/TDD by building this simple blog app. 我决定通过构建此简单的博客应用程序来学习BDD / TDD。 Here is the failure message:
这是失败消息:
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>
The test: 考试:
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
My Factory Girl file: 我的工厂女郎文件:
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
The controller: 控制器:
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
In case it's relevant, here's my Gemfile: 如果相关,这是我的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
Any help is appreciated. 任何帮助表示赞赏。
Try this for your tests: 尝试以下方法进行测试:
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
Personally I'd also separate some of those expects you did in to different tests. 就我个人而言,我还会将您的一些期望与其他测试分开。 However, I don't know that testing that they're set that way is really necessary in a controller.
但是,我不知道在控制器中是否真的需要测试以这种方式设置它们。
edit: There is also an issue with your create action where in the event of it not successfully saving it will still try to redirect to the @post which will fail. 编辑:您的创建操作还有一个问题,如果未成功保存,它仍将尝试重定向到@post,这将失败。 Your test with invalid attributes should highlight this.
具有无效属性的测试应突出显示这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.