thank_you
thank_you

Reputation: 11107

Understanding Rspec Stubs and Controller Tests

My first time I'm using a stub and I have a controller that runs a method when the page is called. If that method returns empty I want a redirect back to the home page. Thus my controller looks like this

def jobs
  if scrap_cl().empty?
    redirect_to home_path
    flash[:error] = "Nothing found this month!"
  end
end

For my test, I want to test the redirect when that method returns empty. So far I have this

context "jobs redirects to homepage when nothing returned from crawlers" do
  before do
    PagesController.stub(:scrap_cl).and_return("")
    get :jobs
  end

  it { should respond_with(:success) }
  it { should render_template(:home) }
  it { should set_the_flash.to("Nothing found this month!")}      

end

When I run rpsec I get the two errors, one on rendering the template and the other on flash. Thus, it's sending me to to the jobs page. What am I doing wrong with the stub and test?

Upvotes: 2

Views: 1336

Answers (1)

Chris Heald
Chris Heald

Reputation: 62698

Your stub there is going to stub out a class method called scrap_cl, which will never be called. You want the instance method. You can get to this easily with RSpec's any_instance:

PagesController.any_instance.stub(:scrap_cl).and_return("")

This will cause all instances of PagesController to stub that method, which is what you actually want here.

Upvotes: 3

Related Questions