2011-01-19 28 views
0

我在RSpec的一個新手,我有這樣的控制器在我的Ruby on Rails的代碼你如何在RSpec中測試這個動作?

def create 
    @article = current_user.articles.build params[:article] 
    if @article.save 
    redirect_to articles_path, :notice => 'Article saved successfully!' 
    else 
    render :new 
    end 
end 

你怎麼會在測試RSpec的這一行動?

謝謝

+2

你想要什麼瞭解呢? – Zinc 2011-01-19 11:00:56

+0

如何模擬current_user對象? – gkrdvl 2011-01-19 11:02:20

回答

6
describe "POST 'create'" do 
    let(:article) { mock_model(Article) } 

    before(:each) do 
     controller.stub_chain(:current_user,:articles,:build) { article } 
    end 

    context "success" do 
     before(:each) do 
     article.should_receive(:save).and_return(true) 
     post :create 
     end 

     it "sets flash[:notice]" do 
     flash[:notice].should == "Article saved successfully!" 
     end 

     it "redirects to articles_path" do 
     response.should redirect_to(articles_path) 
     end 

    end 

    context "failure" do 
     before(:each) do 
     article.should_receive(:save).and_return(false) 
     post :create 
     end 

     it "assigns @article" do 
     assigns(:article).should == article 
     end 

     it "renders new" do 
     response.should render_template('new') 
     end 
    end 

    end