2013-05-07 63 views
1

我在我的应用程序中可以创建帖子的用户模型(代理)。他们可以从他们的仪表板执行此操作。我还会在他们的仪表板中显示他们现有的所有帖子。当尝试创建一个没有内容的新帖子时,问题就出现了,我正在测试它以确保它呈现错误。创建一个包含内容的帖子,但创建一个包含out的文件会一直触发一个错误,表示我的@posts实例变量为零。不知道我是否错过了一些东西?为什么实例变量nil在我的rails部分?

仪表板视图:

.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

+1与测试:) – sameera207 2013-05-07 12:48:04

回答

2

您从posts#create内再现home/dashboard时后有错误,但你不设置@posts变量。

你应该之前render 'home/dashboard'

@posts = current_agent.posts 
+0

综合问题工作就像一个魅力,完全忽略了这一点。干杯 – David 2013-05-07 16:44:45

0

使用redirect_to dashboard_path,而不是render 'home/dashboard'添加此。 ,您可以通过在home#dashboard中调用keep闪光灯的方法在仪表板上保留闪光消息。

flash.keep 
0

如果我正确理解你的问题,你有在装载问题的页面(HomeController的#指数)

,我可以加载索引动作之前看到的,你检查用户是否登录与否,

确保您的应用程序流进入

if current_agent 
     #make sure you application flow comes here 
     @post = current_agent.posts.build 
     @posts = current_agent.posts 
end 

如果没有,你可能要稍微修改这个流程为(如果这符合你的requirm ENT)

if current_agent 
      @post = current_agent.posts.build 
      @posts = current_agent.posts 
else 
    @post = Post.new 
    @posts = [] 
end 

最后它总是好的使用try,当你不知道的对象,你得到

if @posts.try(:any?)