问题
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