Skip to content

Instantly share code, notes, and snippets.

@data-doge
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save data-doge/c3bef91283aaec409f57 to your computer and use it in GitHub Desktop.

Select an option

Save data-doge/c3bef91283aaec409f57 to your computer and use it in GitHub Desktop.
controller testing sinatra example
#### CONTROLLER ####
get '/cats' do
@cats = Cat.all
erb :index
end
post '/cats' do
cat = Cat.new(name: params[:name], product: params[:product])
cat.save ? (redirect '/cats') : (status 400)
end
#### VIEW ####
<h1>THIS IS THE CATS INDEX PAGE</h1>
<form method='post' action='/cats'>
<input type='text' name='name' placeholder='put cat name'>
<input type='text' name='product' placeholder='put cat product'>
<input type='submit' value='create new cat'>
</form>
<ul>
<% @cats.each do |cat| %>
<li>
<h2><%= cat.name %></h2>
<p><%= cat.product %></p>
</li>
<% end %>
</ul>
#### SPEC ####
require 'spec_helper'
describe "CatsController" do
describe "GET /cats" do
before do
@cat = Cat.create(name: Faker::Name.name, product: "van")
get '/cats'
end
it "returns an http status of 200" do
expect(last_response.status).to eq(200)
end
it "returns index.erb" do
expect(last_response.body).to include("<h1>THIS IS THE CATS INDEX PAGE</h1>")
end
it "the template contains all the cats in the DB" do
expect(last_response.body).to include(@cat.name)
end
after do
Cat.destroy_all
end
end
describe "POST /cats" do
describe "if valid request" do
before do
post '/cats', {name: "Chairvan Davis", product: "one van"}
end
it "returns http status of 302" do
expect(last_response.status).to eq(302)
end
it "redirects to /cats" do
expect(last_response.header["Location"]).to include('/cats')
end
it "add a new cat to the database" do
expect(Cat.find_by(name: "Chairvan Davis")).to be_truthy
end
after do
Cat.destroy_all
end
end
describe "if invalid request" do
before do
post '/cats', {name: "", product: "", asdf: "eyyyyy"}
end
it "return status 400" do
expect(last_response.status).to eq(400)
end
it "it doesn't make a new cat" do
expect(Cat.all.length).to eq(0)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment