Reputation: 27852
I am trying to test the following:
-> As a User, I want to be able to create Posts. Each Post has content and also a Category (which is another Model), that I should be able to select from a dropdown.
I have the following step:
When /^I create a post with valid data$/ do
visit new_post_path
# Here it would go the fill for content
# Here it would go the select of category
end
My question is: Where should I define the categories? In a seed file or..?
Edit: My doubts are, that, for example in my (form) view I have:
<div class="field">
<%= f.label :category %><br />
<%= f.select "category_id", options_from_collection_for_select(Category.all, "id", "name") %>
</div>
Once from my step definition I visit the "new" path, it will visit the view, but Category.all will return nothing. How do I fix that?
Thanks
Upvotes: 0
Views: 391
Reputation: 4086
The general answer is, use a library that implements the test data builder pattern to create any data you need in a Given step. Fabrication and Factory Girl, as mentioned in the other answers, are probably the most commonly used test data builders but there are lots of others.
Upvotes: 0
Reputation: 6501
Any background setup you want, i.e. things that your test relies on should be specified in the Given section.
Background:
Given Categories exist
You can then specify in the steps what items you want to be available for the view. e.g. FactoryGirl.create(:category)
or whatever
When the Given is specified with Background it will run before every scenario in the file, great for setting up dependencies.
Upvotes: 2
Reputation: 10208
You can seed the test database, or you can also use a gem like Fabrication with sequences, it would allow you to do generate unique values such as:
Fabricate.sequence(:category) { |i| "Category #{i}" }
# => "Category 0"
# => "Category 1"
# => "Category 2"
Upvotes: 0