您将如何在 RSpec 中测试此操作?

发布于 2024-10-13 09:28:01 字数 310 浏览 0 评论 0原文

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

谢谢

I'm a newbie in RSpec, I have this controller in my ruby on rails code

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

How would you test this action in RSpec ?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神妖 2024-10-20 09:28:01
  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
  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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文