我有功能测试,其中有 2 个重复的部分:

require 'spec_helper'

describe "Messages manage" do
  let (:user) { create :user }
  let (:other_user) { create :use }
  before(:each) do
    login_as user
  end

  describe "[message create]" do

    it "messages created by self, should appear on the page", js: true do
      message_text = "Hello my friend"

      visit user_messages_path(user, {with:other_user.id} )
      fill_in :message_body, with: message_text
      click_button t("users.messages.index.send")
      sleep 1 # waiting for js

      page.should have_content(message_text)
      find_field(:message_body).value.should == ""
      page.should have_selector('#message_body', visible: false)
    end

    it "message errors should be displayed", js: true do
      message_text = "123"

      visit user_messages_path(user, {with:other_user.id} )
      fill_in :message_body, with: message_text
      click_button t("users.messages.index.send")
      sleep 1 # waiting for js

      page.should_not have_content("Message: #{message_text}")
      find_field(:message_body).value.should == message_text
      page.should have_selector('.message.error', visible: true)
    end

  end
end

在这种情况下,使用 shared_examples 或类似方法的最佳方法是什么?到以下DRY。

最佳答案

您可以在代码下方附加特定的方法

require 'spec_helper'

describe "Messages manage" do
  # let (:user) { create :user }
  # Instead expose it as instance variable
  @user = create(:user)
  # let (:other_user) { create :user }
  @other_user = create(:user)
  before(:each) do
    login_as user
  end

  describe "[message create]" do

    it "messages created by self, should appear on the page", js: true do

      # Use the custom method
      send_message "Hello my friend"

      page.should have_content(message_text)
      find_field(:message_body).value.should == ""
      page.should have_selector('#message_body', visible: false)
    end

    it "message errors should be displayed", js: true do

      # Use the custom method
      send_message "123"

      page.should_not have_content("Message: #{message_text}")
      find_field(:message_body).value.should == message_text
      page.should have_selector('.message.error', visible: true)
    end

  end


  def send_message(message_text)
        visit user_messages_path(@user, {with:@other_user.id} )
        fill_in :message_body, with: message_text
        click_button t("@users.messages.index.send")
        sleep 1 # waiting for js
  end

end

对于更通用的代码,您可以将它们提取到模块中的规范/支持中。但是对于这种情况,上面的方法应该已经足够了。

关于ruby-on-rails - Rspec:共享示例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15856862/

10-12 00:53