Rails 3&黄瓜 - 创建关联的步骤定义

时间:2012-07-14 19:50:25

标签: ruby-on-rails ruby-on-rails-3 cucumber capybara

我有两个rails资源:notes&技术。

注意型号:

class Note < ActiveRecord::Base
  belongs_to :technology
end

技术模型:

class Technology < ActiveRecord::Base
  has_many :notes
end

我想使用以下的Capybara步骤:

Scenario: Viewing notes and their technology association
    Given there are the following notes:
      | subject              |
      | recursive functions  |
    And the note "recursive functions" has the technology "JavaScript"
    And I am on the homepage
    Then I should see "recursive functions"
    And I should see "JavaScript"

我用于该行的步骤:

    And the note "recursive functions" has the technology "JavaScript"

是(我怀疑问题出在以下):

Given /^the note "(.*?)" has the technology "(.*?)"$/ do |note, tech|
  @note = Note.find_by_subject!(note)
  @note.technology = Technology.find_or_create_by_name(tech)
end

我想让find_or_create给定的Technology对象的名称(name是Technology对象的参数)并创建关联,以便该笔记属于该技术。

然后,最后一步:

And I should see "JavaScript"

是否验证note.technology.name是否显示在Note#index

上的每个音符实例旁边
  <% @notes.each do |note| %>
    <li>
      <%= link_to note.subject, note %> 
        <% if note.technology %>
          | Tech: <%= note.technology.name %>        
        <% end %>
    </li>
  <% end %>

当我运行这个Cucumber功能时,步骤会一直传到最后,我应该看到“JavaScript”,错误:

expect there to be content "JavaScript" in "Note Index Page"
recursive functions \n \n recursive functions \n \n (RSpec:Expectations::ExpectactionNotMetError
./features/step_definitions/web_steps.rb:107 in '/^(?:|I )should see "([^"]*)"$/'
features\viewing_notes.feature:20:in 'And I should see "JavsScript"'

我知道该关联正在起作用,因为创建与表单的关联起作用(并在Note#index上显示@ note.technology.name)。问题似乎与我的步骤定义有关。有没有更好的方法来测试这个,看看发生了什么?也许写一个Rspec规范?感谢您抽出宝贵时间提供帮助。

(可能相关:)

gem 'rails', '3.0.0'

group :test do
  gem 'rspec-rails', '2.0'
  gem 'factory_girl', '2.6.4'
end

group :cucumber do
  gem 'cucumber-rails', '1.0.6'
  gem 'capybara'
end

1 个答案:

答案 0 :(得分:2)

快速回答:

@note.technology = Technology.find_or_create_by_name(tech)
@note.save