Rspec条件断言:has_content A OR has_content B

时间:2011-11-01 01:11:46

标签: ruby-on-rails testing rspec

我知道这将是一个非常新手的问题,但我不得不问它......

如何使用逻辑OR和AND和Rspec链接不同的条件?

在我的示例中,如果我的页面包含任何这些消息,则该方法应返回true。

def should_see_warning
  page.should have_content(_("You are not authorized to access this page."))
  OR
  page.should have_content(_("Only administrators or employees can do that"))
end

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

如果给定相同的输入/设置产生不同或隐含的输出/期望,您通常不会编写测试。

这可能有点单调乏味,但最好根据请求时的状态分离您的预期回复。读到你的榜样;您似乎正在测试用户是否已登录或授权然后显示消息。如果你将不同的状态分解为上下文并针对每种消息类型进行测试会更好:

# logged out (assuming this is the default state)
it "displays unauthorized message" do
  get :your_page
  response.should have_content(_("You are not authorized to access this page."))
end

context "Logged in" do
  before
    @user = users(:your_user) # load from factory or fixture
    sign_in(@user) # however you do this in your env
  end

  it "displays a permissions error to non-employees" do
    get :your_page
    response.should have_content(_("Only administrators or employees can do that"))
  end

  context "As an employee" do
    before { @user.promote_to_employee! } # or somesuch
    it "works" do
      get :your_page
      response.should_not have_content(_("Only administrators or employees can do that"))
      # ... etc
    end
  end
end