1

我正在使用 rails rspec/capybara/declarative_authorization。我必须对很多不同的用户运行相同的测试:

 describe "Revision in root folder" do
   before do
     with_user(@guest) do
       visit revisions_path
     end
   end
   it { should have_selector('div.alert.alert-error', text: auth_error_text) }
 end
...
 describe "Revision in root folder" do
   before do
     with_user(@user1) do
       visit revisions_path
     end
   end
   it { should have_selector('div.alert.alert-error', text: auth_error_text) }
 end

唯一的参数是调用with_user的用户。我能否以某种方式只使用一个描述块,并遍历一组用户,以保持我的测试 DRY。重要的是,@guest 和 @user1 是在before(:all)块中创建的,因此在解析规范时它们不可用。

任何帮助表示赞赏。

4

4 回答 4

2
describe "Revision in root folder" do
  users = [@guest, @user1]
  users.each do |user|
    before do
      with_user(user) do
        visit revisions_path
      end
    end
    it { should have_selector('div.alert.alert-error', text: auth_error_text) }
  end
end
于 2013-04-15T13:32:17.357 回答
0

没有那么多 DRYer,但你介意嵌套你的规格吗?这样,您就可以考虑用户和来宾之间的任何不同的预期行为。

describe "Revision in root folder" do
  context "as a guest" do
    before do
      with_user(@guest) do
        visit revisions_path
      end
    end
    it { should have_selector('div.alert.alert-error', text: auth_error_text) }
  end

  context "as a user" do
    before do
      with_user(@user1) do
        visit revisions_path
      end
    end
    it { should have_selector('div.alert.alert-error', text: auth_error_text) }
  end
end

如果您最终得到更多重复的it语句,您可能可以将它们重构为共享示例

于 2013-04-15T13:56:38.257 回答
0

现代版本的 Rspec 允许在没有猴子补丁的情况下复制示例。请看一下这个要点https://gist.github.com/SamMolokanov/713efc170d4ac36c5d5a16024ce633ea

可能会提供不同的用户作为shared_context-user将在实际测试中可用:

  shared_context "Tested user" do
    let(:user) { |example| example.metadata[:user] }
  end

在克隆期间,我们可以做

  USERS.each { |user| example.duplicate_with(user: user) }
于 2019-02-21T13:04:10.480 回答
0

我有同样的问题,我通过以下方式解决它:

[:user_type_1, :user_type_2].each do |user_type|
   let(:user) { create(user_type) }
   before do
     with_user(user) do
       visit revisions_path
     end
   end
   it { should have_selector('div.alert.alert-error', text: auth_error_text) }
end
于 2017-02-24T09:41:04.497 回答