如何在rspec中跨上下文使用变量

时间:2011-09-29 15:33:54

标签: ruby-on-rails rspec

在下面的代码中,每次调用subscriber_with_99_users都会创建一个拥有99个用户的新订阅者,这是我不想要的。我如何解决这个问题只是创建一次订阅者并在所有后续调用中返回它,或者有更好的方法来执行此操作。

describe "#as_json" do

context "in 'users' path for a subscriber with 99 users" do

  let(:presenter_options) { { path: 'users', page: 1, per_page: 10 } }

  let(:subscriber_with_99_users) {
    if (@subs_with_99_users)
      @subs_with_99_users
    else
      @subs_with_99_users = get_subscriber_with_many_users 99
    end
  }

  subject { subscriber_presenter.as_json.fetch('users').length } 

  context "and pagination with page size of 10" do 

    {1 => 10, 10 => 9, 11 => 0, 100 => 0}.each do |page, count|
      context "for page #{page}" do
        let(:subscriber_presenter) { 
          Fabricate(:subscriber_presenter, subscriber: subscriber_with_99_users, options: presenter_options.merge(page: page)) 
        }
        it "returns #{count} users" do
          should == count
        end
      end
    end

  end

end

end                                                     

1 个答案:

答案 0 :(得分:1)

如果您尝试跨越上下文执行操作,则可能需要关闭事务性设备。这很容易做到

ActiveSupport::TestCase.use_transactional_fixtures = false

虽然如果你可以在Before块中策略性地设置变量可能会更好:

https://www.relishapp.com/rspec/rspec-core/v/2-13/docs/hooks/before-and-after-hooks