Rspec组织

时间:2011-08-28 01:17:43

标签: ruby-on-rails rspec

我目前正在使用带有cancan的rspec。我意识到乱丢许可控制测试用例遍布我的控制器spec文件非常混乱。基本上,我的几乎每个控制器规范文件都有类似的东西:

  describe "failure" do 
    it { get :new }
    it { get :edit, :id => @deal }
    it { get :update, :id => @deal }
    it { get :destroy, :id => @deal }

    after(:each) do
      response.should_not be_success
      response.should redirect_to(root_path)
      flash[:error].should == "Permission denied."
    end
  end
end

我的系统中有4个角色,这无疑使组织成为一项更加困难的任务。

由于所有这些测试都与权限控制/ ACL相关,我尝试将它们全部放在一个文件中rspec / models / ability_spec.rb

现在,我的ability_spec看起来像这样:

describe "cancan" do 
  it "failure" do 
    @ability.should_not be_able_to(:all, Factory(:purchase))
    @ability.should_not be_able_to(:all, Factory(:user))
    @ability.should_not be_able_to(:all, Visit)
  end
end

我收到以下错误:

  6) Ability consumers deals failure 
     Failure/Error: it { get :destroy, :id => @deal }
     NoMethodError:
       undefined method `get' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1::Nested_2::Nested_2:0x007fd73209a270>
     # ./spec/models/ability_spec.rb:46:in `block (5 levels) in <top (required)>'

我知道我不应该把控制器get / post放在这个文件中。有没有办法这样做是为了简化我的权限相关测试的测试?

1 个答案:

答案 0 :(得分:1)

查看RSpec的共享示例,看看是否可以将任何内容提取到共享示例组中:

http://relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples