简体   繁体   中英

RSpec Controller Testing Error

I am very new to RSpec. I am trying to do a basic controller test for Rails app. I want to check that when I use the PostsController's "create" action, the user gets redirected to the posts path. Here is my current test.

 describe "POST #create" do 
  it "returns http success" do
   post :create, {'post' => { :title => "My first post", :author => 'Jack Seabolt'} }
   expect(response). to have_http_status(:success) 
  end

  it "redirects to 'index' template" do 
   post :create , {'post' => {:title => "my first post", :author => 'Jack Seabolt'} }
   expect(response) redirect_to(posts_path)
  end 
end 

This code leads to this error:

/Users/johnseabolt/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `load':    
/Users/johnseabolt/Desktop/projects/tdd/spec/controllers/posts_controller_spec.rb:49: syntax error, unexpected tIDENTIFIER, expecting keyword_end (SyntaxError)
  expect(response) redirect_to(posts_path)
                              ^

I've attempting adding just 'posts'. I tried 'index'. Didn't work. If someone could point me in the right direction, I would appreciate it. Thanks.

你已经错过了调用一个方法to用于expect

expect(response).to redirect_to(posts_path)

Usually the formula for an expectation is something like:

expect( something ).to eq another_thing
expect( something ).to be another_thing

or

expect( something ).to_not eq another_thing
expect( something ).to_not be another_thing

In your case, you don't need the be or eq cause of the redirect_to matcher.

expect(response).to redirect_to(posts_path)

DOCS:

docs for redirect_to matcher: https://www.relishapp.com/rspec/rspec-rails/v/3-5/docs/matchers/redirect-to-matcher

docs for be matchers: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/be-matchers

docs for eq matchers: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/equality-matchers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM