Rspec2 partial view gives nil:NilClass. Why?

2019-06-14 12:51发布

问题:

I am trying to get going with development of view components with Rspec2 and Rails3. However, I make the following observation, and I don't understand what is going on, and how to fix this.

In my spec I define:

  describe "main/index.html.erb" do
    it "displays a photo url in products partial" do
      assign(:designs, [stub_model(Design, :name => "test", :photo => "photo_url")])

      render
      rendered.should contain("photo_url")
    end
  end

When I run:

rspec spec/view/main_spec.rb

I get this error:

    1) main/index.html.erb displays a photo url in products partial
       Failure/Error: render
       ActionView::Template::Error:
         undefined method `photo' for nil:NilClass
       # ./app/views/main/_design.html.erb:3:in   `_app_views_main__design_html_erb__2937334847274155273_2170841960__1566661024965846011'
       # ./app/views/main/index.html.erb:25:in `_app_views_main_index_html_erb__837234277009287876_2170861440__898201527838028543'
       # ./spec/views/main_spec.rb:7:in `block (2 levels) in '

However, if I only 'access' a local photo object in my partial everything passes. This is:

in _design.html.erb:

        ---> PASS
        ---> FAIL

In my view I call my partial as follows:

main.html.erb

      { :designs => @designs } %> 

What does the community think? Thank you for your help!

回答1:

The problem has been solved some while ago already.

It is important to keep "convention over configuration" in mind. In this case, the spec could be made working by naming the spec files exactly to the filenames in the /app folder and putting a _spec.rb at the end. So, the right spec for the index erb in main would be

/spec/views/main/index.erb_spec.rb