我的应用中有一个可以创建帖子的用户模型(代理)。他们可以通过仪表板完成此操作。我还会在其信息中心内显示所有现有帖子。当我尝试创建一个没有内容的新帖子时,我正在测试以确保它呈现错误。创建一个包含内容的帖子,但创建一个没有内容的帖子会一直触发一个错误,表明我的@posts实例变量为零。不确定我是否错过了什么?
仪表板视图:
.container
.column.span9
- if current_agent
= render 'home/shared/agent_post_panel'
= render 'home/shared/agent_dashboard_tabs'
agent_dashboard_tabs:
.tabs-container
#posts
.content
- if @posts.any? //This is where the error is triggered
= render partial: 'shared/post', collection: @posts
仪表板控制器:
class HomeController < ApplicationController
before_filter :authenticate!, only: [:dashboard]
def index
end
def dashboard
if current_agent
@post = current_agent.posts.build
@posts = current_agent.posts
end
end
end
我的帖子控制器:
class PostsController < ApplicationController
before_filter :authenticate_agent!
def create
@post = current_agent.posts.build(params[:post])
if @post.save
flash[:notice] = "Post created!"
redirect_to dashboard_path
else
flash[:error] = "Post not created"
render 'home/dashboard'
end
end
end
试验:
feature 'Creating posts' do
let(:agent) { FactoryGirl.create(:agent) }
before do
sign_in_as!(agent)
visit dashboard_path
end
scenario "creating a post with valid content" do
fill_in 'post_content', :with => 'I love donuts'
expect { click_button "Post" }.to change(Post, :count).by(1)
end
scenario "creating a post with invalid content" do
expect { click_button "Post" }.not_to change(Post, :count)
click_button "Post"
page.should have_content("Post not created")
page.should have_content("can't be blank")
end
答案 0 :(得分:2)
当帖子有错误时,您正在home/dashboard
内呈现posts#create
,但您没有设置@posts
变量。
您应该在render 'home/dashboard'
@posts = current_agent.posts
答案 1 :(得分:0)
使用redirect_to dashboard_path
代替render 'home/dashboard'
。
您可以在keep
中调用home#dashboard
闪存方法,在信息中心上保留Flash消息。
flash.keep
答案 2 :(得分:0)
如果我理解你的问题,你在加载页面时遇到问题(HomeController #index)
正如我在加载索引操作之前所看到的那样,您可以检查用户是否已登录,
确保您的申请流程进入
if current_agent
#make sure you application flow comes here
@post = current_agent.posts.build
@posts = current_agent.posts
end
如果不是,您可能需要稍微修改此流程(如果这符合您的要求)
if current_agent
@post = current_agent.posts.build
@posts = current_agent.posts
else
@post = Post.new
@posts = []
end
最后使用try
总是好的,当你不确定你得到的对象时
if @posts.try(:any?)