CalebHC
CalebHC

Reputation: 5042

How do I test a nested resource view in RSpec using Rails 4.2?

I'm trying to test a view that has a nested resource path but the test keeps failing and saying that a key is missing. I figure it is missing a key from the path but I don't know how to set it.

require 'rails_helper'

RSpec.describe 'maintenance_request_forms/new.html.haml', type: :view do
  before do
    assign(:form, FactoryGirl.build(:maintenance_request_form))
  end

  it 'show the submit button' do  
    render

    expect(rendered).to match /Submit Request/
  end
end

So anyone know of a way to set a url parameter in a view spec? Thanks!

Edit

I was notified that this question may be a duplicate of another but I already saw that other question before writing this one. Sadly none of the solutions in that question helped. The other question's answer was to extract the problem code into a helper and then unit test that. Much different than what problem I was facing when trying to set params in the rendering of a rails path method.

Closing This Question

I posted my alternative way to set params on the other question and voted this question to be closed.

Upvotes: 0

Views: 474

Answers (1)

CalebHC
CalebHC

Reputation: 5042

Well I finally figured it out after digging through the RSpec source code! You actually can set path params by using:

controller.request.path_parameters[:some_param] = 'a value'

After setting the param I needed for the path my spec started passing. :) I'm really not sure if this is the best solution but the solution does seem rather simple.

Thanks!

Here's what my spec looks like now:

require 'rails_helper'

RSpec.describe 'maintenance_request_forms/new.html.haml', type: :view do
  before do
    assign(:form, FactoryGirl.build(:maintenance_request_form))
    controller.request.path_parameters[:request_form_id] = 1
  end

  it 'show the submit button' do  
    render

    expect(rendered).to match /Submit Request/
  end
end

Upvotes: 1

Related Questions