I am having trouble testing my controller's update action using Rspec, what am I doing wrong?

我怕爱的太早我们不能终老 提交于 2019-12-05 08:01:01

问题


I am trying to test the failing branch of the update action on my controller but I am having trouble with the test. This is what I have and it fails on the last

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

Any ideas as to why the last part fails to render the template?


回答1:


You're splitting up the parts of your test incorrectly. Each it call is actually a new example and the state is reset before/after each one.

What you should be doing is:

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

By doing it this way, the @article is set up before hand (although you could use a mock one if you really wanted to) and the request to the update action and the assertion that it actually renders the edit template all happen in the one example.




回答2:


For people who are coming here in 2018, some updates(pun not intended) have been made. It's important to include "params" before listing the params. Additionally, you should use expect and not "should" since it will be deprecated in 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


来源:https://stackoverflow.com/questions/7060521/i-am-having-trouble-testing-my-controllers-update-action-using-rspec-what-am-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!