Installing
1) Add:
ENV["RAILS_ENV"] = "test"
to the top of /spec/spec_helper.rb
2) Add:
config.gem "niessner-rspec_controller_macros"
to your environment.rb inside the Initializer.run block
Usage
Register roles by adding code similar to the following in the configure block of your spec/spec_helper.rb
Rspec::UserRoles.register(:visitor) nil Rspec::UserRoles.register(:user) User.new
Rspec::UserRoles.register(:admin) do
user = User.new
user.admin = true
user
end
You can write specs that work similar to what’s below.
describe Admin::ArticlesController do
describe "get index" do
as_a(:visitor) {it_should_redirect_to {new_session_path}}
as_a(:user) {it_should_render_template.}
as_an :admin do
before do
@articles = [Article.new, Article.new]
stub(Article).find(:all) {@articles}
end
it_should_render_view Admin::Articles::Index
it_should_render_layout Layouts::Admin
it_should_set_rendered_view.articles.to {@articles}
end
end
describe "post create" do
as_a(:visitor) {it_should_redirect_to {new_session_path}}
as_a(:user) {it_should_render_template.}
as_an :admin do
before {stub(Article).create!("title" => "Title", "body" => "Body")}
post :article => {:title => "Title", :body => "Body"}
it "should call finishing_editing" do
response.should have_text("finish_editing(null);")
end
end
end
describe "post update" do
as_a(:visitor) {it_should_redirect_to {new_session_path}}
as_a(:user) {it_should_render_template.}
as_an :admin do
before(:each) do
article = Article.new
strong.stub(Article).find("5") {article}
strong.stub(Article).find(:all) {[]}
strong.stub(article).update_attributes!("title" => "Title", "body" => "Body")
end
post :id => 5, :article => {:title => "Title", :body => "Body"}
it "should call finishing_editing" do
response.should have_text("finish_editing(null);")
end
end
end
describe "post publish" do
as_a(:visitor) {it_should_redirect_to {new_session_path}}
as_a(:user) {it_should_render_template.}
as_an :admin do
before(:each) do
@article = Article.new
strong.stub(@article).publish!
strong.stub(Article).find("5") {@article}
strong.stub(Article).find(:all) {[]}
end
post :id => 5
it "should publish the article" do
verify_invocation of_spy(@article).publish!
end
end
end
describe "post destroy" do
as_a(:visitor) {it_should_redirect_to {new_session_path}}
as_a(:user) {it_should_render_template.}
as_an :admin do
before(:each) do
@article = Article.new
strong.stub(@article).destroy
strong.stub(Article).find("5") {@article}
strong.stub(Article).find(:all) {[]}
end
post :id => 5
it "should destroy the article" do
verify_invocation of_spy(@article).destroy
end
end
end
end