4

In my application I have a topic controller and I need to write a test case for creating a new topic. when a new topic is created it will be redirected to the show page of the newly created topic and a notice will be displayed "Topic was created successfully!". I need to write a test case for checking the displayed notice is correct or not using rspec.I have the topic controller:

 def create
@topic = Topic.new(topic_params)
if (@topic.save)
  redirect_to @topic, :notice => 'Topic was created successfully!'
else
  render :action => 'new'
end
end

TopicController spec:

it "should create new Topic and renders show" do
    expect {
      post :create,params:{ topic:{topicname: "Tech"} }
    }.to change(Topic,:count).by(1)
    expect(response).to redirect_to(topic_path(id: 1))
   /// expect().to include("Topic was created successfully!")
  end

Already I have written test cases for redirecting to show page. But I am stuck with the checking the notice that I have mentioned in a comment in my code.

Praveen R
  • 160
  • 11

2 Answers2

4

You should do something like this

expect(flash[:notice]).to match(/Topic was created successfully!*/)
2

Use a feature spec (an integration test) instead of a controller spec to test the application as seen by the user:

# spec/features/topics.rb
require 'rails_helper'
RSpec.feature "Topics" do
  scenario "when I create a topic with valid attributes" do
    visit '/topics/new'
    fill_in 'Topicname', with: 'Behavior Driven Development' # Adjust this after whatever the label reads
    click_button 'create topic'
    expect(page).to have_content 'Topic was created successfully!'
  end

  scenario "when I create a topic but the attributes are invalid" do
    visit '/topics/new'
    fill_in 'Topicname', with: ''
    click_button 'create topic'
    expect(page).to_not have_content 'Topic was created successfully!'
    expect(page).to have_content "Topicname can’t be blank"
  end
end

While you can poke around the flash hash you should have an integration test covering this anyways since controller tests are flawed and will not cover for example errors in the routes since large portions of the application are stubbed out.

In fact you may want to reconsider using controller specs at all since both the RSpec and Rails teams suggest using integration testing instead. If you want to test at a lower level than a feature spec use request specs.

See:

max
  • 76,662
  • 13
  • 84
  • 137