views:

304

answers:

2

So in my feature file, I have a login background step:

Given /^I login$/ do
  user = Factory(:user)
  visit '/login'
  fill_in("login", :with => user.login)
  fill_in("password", :with => user.password)
  click_button("Login")
  @current_user = user
end

In the next step, I want to be able to include a user_id, but not sure how to get the @current_user that I have logged in.

Given a post exists with name: "My Post", category_id: 3, user_id: ?????

How can I use @current_user to create the correct relationship?

Thanks.

A: 

Let the step figure out the id instead of trying to pass it in.

Given /^a post exists with name: "([^\"]+)", category_id: (\d+)$/ do |name, category_id|
  @post = Post.create!(:name => name, :category_id => category_id, :user_id => @current_user.id)
end

If this were my code, I'd probably get :category_id out of there, too. I take technical stuff like object IDs showing up in my scenario descriptions up as a sign I'm getting too low level with them.

Baldu
That's actually a pickle step where you pass other attributes in. I guess I may just have to define the step myself.
Avoidiam
Or if in my factory, I could do something like:Factory.define :post do |p| p.user_id @current_user.id p.category_id 2end
Avoidiam
Ah, I see. I hadn't seen pickle before. I'm not sure I like it, to be honest. You start to loose the plain english aspect, which is one of the strengths of cucumber. Personal preference, I know, but I would have said some like Given a post named "My Post" in the category "Duck sauce". Or something like that. Your steps end up a easier to reuse, but read awkwardly.
Baldu
+1  A: 

If you reword it thusly:

Given I created a post with the title "My Post" in the "foobar" category

Then it should be most obvious as to how you should implement it:

Given /^I created post with the title "([^\"]+)" in the "([^\"]+)" category/ do |title, category|
    current_user.posts.create!(
        :title => title, 
        :category => Category.find_or_create_by_name(category))
end

Obviously this depends on how you've structured your associations, but it should work. If you're using Factory Girl, then it'd be something like:

Factory.create(:post, :category => ..., :user => current_user)

Don't forget that your cucumber specs should be in the terms of what the user sees, and does, not in the way your system works, so as Baldu says keep record ids out of the step definitions.

jonnii
Sorry, I'm trying to do this using pickle. For now I rewrote it similar to how you said, but I'd really like to take advantage of pickle.
Avoidiam