我在我的應用程序中可以創建帖子的用戶模型(代理)。他們可以從他們的儀表板執行此操作。我還會在他們的儀表板中顯示他們現有的所有帖子。當嘗試創建一個沒有內容的新帖子時,問題就出現了,我正在測試它以確保它呈現錯誤。創建一個包含內容的帖子,但創建一個包含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
+1與測試:) – sameera207 2013-05-07 12:48:04