你会如何在RSpec中测试这个动作?

时间:2011-01-19 10:54:52

标签: ruby-on-rails-3 rspec2

我是RSpec的新手,我的ruby on rails代码中有这个控制器

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中测试此操作?

谢谢

1 个答案:

答案 0 :(得分: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