Question

I have a Page resource for which the create action in the pages_controller.rb file looks as follows:

def create
  @page = Page.new(page_params)
    if @page.save
      flash[:notice] = "#{@page.name} was created successfully."
      redirect_to pages_url
    else
      render 'new'    
  end
end

private
  def page_params
    params.require(:page).permit(:name, :content)     
end

And the following test in the pages_controller_spec.rb file:

describe PagesController do
  describe "POST Create'" do
    it "creates a new page" do
      Page.should_receive(:new)
      post :create, page: {name: "Foo", content: "Bar"}
    end
  end
end

Which produces the following error: undefined method 'save' for nil:NilClass

I'm just starting out with RSpec; so surely I've either made a mistake or I am overlooking something simple. Also, I'm following the "RSpec Book", which goes on to add: page = mock_model(Page).as_null_object right before Page.should..., but I'm still getting the same error. Any ideas? Thanks in advanced.

Was it helpful?

Solution

With

Page.should_receive(:new)

you're essentially stubbing it. This is short for:

Page.should_receive(:new).and_return(nil)

That's why you're getting the error on nil:NilClass. What you could do is either chaining a call to and_call_original, which would look like this:

Page.should_receive(:new).and_call_original

or you specifically return a mock, something along the lines of:

Page.should_receive(:new).and_return(mock_model(Page))

OTHER TIPS

Do you have the page.yml in fixture folder may be because of that it not saving the page.In my app i have added the blue print.rb for structure of my model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top