Hommer Smith
Hommer Smith

Reputation: 27852

How to add context in a feature rspec?

I want to add context into my feature rspec, but I am not sure what makes sense between context and scenario.

Here is what I have so far:

feature 'As an admin I manage the orders of the system' do
  context 'Logged in user who is an admin' do
    before(:each) do
      admin = create(:admin_user)
      login_as(admin, :scope => :user)
    end

    scenario 'User sees all the orders' do
      visit admin_orders_path
      expect(page).to have_content('List of orders')
    end
  end

  context 'Logged in user who is not an admin' do
    before(:each) do
      user = create(:user)
      login_as(user, :scope => :user)
    end

    scenario 'User cannot see the orders' do
      visit admin_orders_path
      expect(current_path).to eq('/')
    end
  end

end

Does this makes sense, or I should decide between using scenario or context, but not both together?

Upvotes: 1

Views: 3715

Answers (2)

appostolis
appostolis

Reputation: 2303

The way I am thinking my tests is the following:

Feature specs are high-level tests for testing the whole "picture" - functionality of your application.

So, core functionality of my app: features with scenarios inside.

Unit tests: describe and it.

You can use context in both though.

From the documentation: The feature and scenario correspond to describe and it, respectively. These methods are simply aliases that allow feature specs to read more as customer tests and acceptance tests.

So, in your case I would do the following:

feature 'As an admin I manage the orders of the system' do
  context 'user is logged in as' do 

    before(:each) do
      user = create(:user)
      login_as(user, :scope => :user)
    end

    scenario 'an admin, can see all the orders' do
       visit admin_orders_path
       expect(page).to have_content('List of orders')
     end

    scenario 'not an admin, cannot see the orders' do
      visit admin_orders_path
      expect(current_path).to eq('/')
  end
end

One context, two scenarios for the user. Also, I would think a little bit more about the description of the feature. Hope that helps and doens't confuse you more!

Also, I like to see my tests like the "heartbeat" of my app. First, you go from feature testing (outside, core functionality) and then you go inside(unit test). And that thing is repeating all the time, like a "heartbeat"

Upvotes: 2

zetetic
zetetic

Reputation: 47548

According to the docs:

The feature and scenario DSL correspond to describe and it, respectively. These methods are simply aliases that allow feature specs to read more as customer tests and acceptance tests.

You can simply replace describe (or context) with feature when writing feature specs. The feature statement should work when nested, like describe.

Upvotes: 1

Related Questions