【问题标题】:I am having trouble testing my controller's update action using Rspec, what am I doing wrong?我在使用 Rspec 测试控制器的更新操作时遇到问题,我做错了什么?
【发布时间】:2011-08-14 23:44:45
【问题描述】:

我正在尝试在我的控制器上测试更新操作的失败分支,但我在测试时遇到了问题。这就是我所拥有的,最后失败了

describe "PUT 'article/:id'" do
.
.
.
  describe "with invalid params" do
    it "should find the article and return the object" do
      Article.stub(:find).with("1").and_return(@article)
    end

    it "should update the article with new attributes" do
      Article.stub(:update_attributes).and_return(false)
    end

    it "should render the edit form" do
      response.should render_template("edit")
    end
  end
end

关于为什么最后一部分无法呈现模板的任何想法?

【问题讨论】:

    标签: ruby-on-rails-3 tdd bdd rspec2


    【解决方案1】:

    您错误地拆分了测试的各个部分。每个it 调用实际上是一个新示例,并且在每个调用之前/之后重置状态。

    你应该做的是:

    describe "with invalid params" do
      before do
        @article = Article.create(valid_params_go_here)
      end
    
      it "should find the article and return the object" do
        put :update, { :id => @article.id, :article => { :title => "" } }
        response.should render_template("edit")
      end
    end
    

    通过这种方式,@article 是事先设置好的(尽管如果您真的想要的话,您可以使用一个模拟的)和对 update 操作的请求和断言它实际上呈现edit 模板都发生在一个示例中。

    【讨论】:

    • 感谢您的回复。所以如果我把它们合二为一会更好。这是测试它的正确方法吗? it "should find the article and return the object" doArticle.stub(:find).with("1").and_return(@article)Article.stub(:update_attributes).and_return(false)put :update, { :id => "1", :article => {:title => nil}}response.should render_template("edit")end
    • @luis:是的,你可以那样做。
    【解决方案2】:

    对于 2018 年来到这里的人,我们进行了一些更新(双关语并非有意)。在列出参数之前包含“参数”很重要。此外,您应该使用 expect 而不是“应该”,因为它会在 Rails 6.0 中被弃用。

    describe "with invalid params" do
      before(:each) do
        @article = Article.create(valid_params_go_here)
      end
    
    describe "PATCH update/:id" do
      it "should find the article and return the object" do
        put :update, params: { id: @article.id, article: { title: "" } }
        expect(response).to be_redirect
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多