ruby-on-rails - 在嵌套 Rspec 上下文中继承示例

标签 ruby-on-rails ruby testing rspec

如何重用示例,以便只覆盖嵌套上下文的细节?

类似这样的事情(我使用 thee 而不是它,这表明它是在嵌套上下文中执行的。它不在 RSpec 中,正是我想要的):

describe "Abilities" do
  subject { Abilities.new user }

  context "allowed" do
    let(:user) { Factory(:power_user) }
    thee { should be_able_to :create, object }
    thee { should be_able_to :read, object }
    thee { should be_able_to :update, object }

    context "comment" do
      let(:object) { Factory(:comment) }
    end

    context "post" do
      let(:object) { Factory(:post) }
    end

    context "blog" do
      let(:object) { Factory(:blog) }
    end

  end
end

此示例最终会针对 3 个上下文(评论、帖子、博客)生成 3 个示例(创建、阅读、更新),从而导致总共 9 个示例。

如何实现它(不编写共享示例)?

最佳答案

没有办法继承例子,但你可以创建一个类方法:

describe "Abilities" do
  subject { Abilities.new user }

  def self.should_allow_stuff
    it { should be_able_to :create, object }
    it { should be_able_to :read, object }
    it { should be_able_to :update, object }
  end

  context "allowed" do
    let(:user) { Factory(:power_user) }

    context "comment" do
      let(:object) { Factory(:comment) }
      should_allow_stuff
    end

    context "post" do
      let(:object) { Factory(:post) }
      should_allow_stuff
    end

    context "blog" do
      let(:object) { Factory(:blog) }
      should_allow_stuff
    end

  end
end

如果需要,您可以根据需要进行重构。

关于ruby-on-rails - 在嵌套 Rspec 上下文中继承示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7829901/

相关文章:

javascript - 使用 npm test 进行 sails.socket 测试

php - 如何测试 WebSocket + PHP 应用程序?

mysql - Rails 使用哈希更新多条记录

ruby - 查找数据库中大量数据的词频

ruby-on-rails - Rails 从 3.2.3 升级到 3.2.11

ruby-on-rails - 部署到 slicehost 时出现 Capistrano 错误

ruby-on-rails - Windows jRuby 上 strftime 的 Unicode 问题

PHPUnit StackTest::assertEmpty() 已弃用

sql - Reddit 如何排序查询他们的数据库 "what' s hot”?

ruby-on-rails - 在 model.save 或 model.save 中捕获数据库异常!方法?