0

I am a newbie to rails and rspec. I am using

rspec-rails 3.0.0

rspec 3.0.0

ruby 2.3.5

I wrote a sample controller

class BaseClass::SampleController < ApplicationController
  skip_before_filter :check_privilege
  def choose
     @page_title = I18n.t('BaseClass.box.chooser_title')
     render :layout => false
end 
end

where

BaseClass.box.chooser_title

is in config/locale/en.yml and it's value is "sample title"

I also have choose.html.erb in app/view and it has title sample title

And I wrote some Rspec for the above controller

context "choose" do
it "renders the choose template" do 
    get :choose
    expect(response).to render_template('choose')
end

it "page title should be Sample title " do
    get :choose
    BaseClass::SampleController.any_instance.stubs(:page_title).returns("Sample title") 
    obj = BaseClass::SampleController.new
    expect(obj.page_title).to eql "Sample title"
end

I want to check whether the title of choose.html.erb is "sample text" or not. I have two questions

  1. I tried writing a stub for the controller in the second test case, the test case runs successfully even when I change the :page_title to some other name(It's not referencing : page_title in BaseClass::SampleController) why?

  2. if not stub how can I access page_title in the spec to check?

Balaji Radhakrishnan
  • 1,010
  • 2
  • 14
  • 28

1 Answers1

1

If you just want to check the title, you don't really need stubs. Try this:

it "page title should be Sample title " do
    get :choose
    expect(assigns(:page_title)).to eq "Sample title"
end

You can read more about this method here

Dabrorius
  • 1,039
  • 1
  • 8
  • 17
  • Thank you it worked. sorry to add one more question. In this case, if I want to access :page_title using a stub how should I do it?. I just want to know this because I couldn't understand stub's syntax at all. Thanks in advance! – Balaji Radhakrishnan Mar 03 '15 at 09:35
  • 1
    You don't really use stubs to "access" stuff, you use it change what some method returns. It's usually used to abstract some part of the application that you don't want to deal with in current test. On the other hand I believe your code would work if you used "BaseClass::SampleController.any_instance.stub" instead of "stubs" to stub a method, but I believe it still wouldn't be a correct approach. Also you might find this SO question interesting http://stackoverflow.com/questions/16005281/rspec-how-to-assign-instance-variable-in-controller-spec – Dabrorius Mar 03 '15 at 09:49